📅  最后修改于: 2020-10-15 01:22:12             🧑  作者: Mango
在冒泡排序中,将数组的每个元素与其相邻元素进行比较。该算法以遍历方式处理列表。具有n个元素的列表需要n-1次传递才能进行排序。考虑由n个元素组成的数组A,其元素将通过使用冒泡排序进行排序。该算法的过程如下。
Scenario | Complexity |
---|---|
Space | O(1) |
Worst case running time | O(n2) |
Average case running time | O(n) |
Best case running time | O(n2) |
#include
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}
输出:
Printing Sorted Element List . . .
7
9
10
12
23
34
34
44
78
101
#include
using namespace std;
int main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
cout <<"Printing Sorted Element List ...\n";
for(i = 0; i<10; i++)
{
cout <
输出:
Printing Sorted Element List ...
7
9
10
12
23
23
34
44
78
101
public class BubbleSort {
public static void main(String[] args) {
int[] a = {10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(int i=0;i<10;i++)
{
for (int j=0;j<10;j++)
{
if(a[i]
输出:
Printing Sorted List . . .
7
9
10
12
23
34
34
44
78
101
using System;
public class Program
{
public static void Main()
{
int i, j,temp;
int[] a = {10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
Console.WriteLine("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
Console.WriteLine(a[i]);
}
}
}
输出:
Printing Sorted Element List . . .
7
9
10
12
23
34
34
44
78
101
a=[10, 9, 7, 101, 23, 44, 12, 78, 34, 23]
for i in range(0,len(a)):
for j in range(i+1,len(a)):
if a[j]
输出:
Printing Sorted Element List . . .
7
9
10
12
23
34
34
44
78
101
fn main()
{
let mut temp;
let mut a: [i32; 10] = [10, 9, 7, 101, 23, 44, 12, 78, 34, 23];
for i in 0..10
{
for j in (i+1)..10
{
if a[j] < a[i]
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
println!("Printing Sorted Element List ...\n");
for i in &a
{
println!("{} ",i);
}
}
输出:
Printing Sorted Element List . . .
7
9
10
12
23
34
34
44
78
101
4
Bubble Sort
输出:
Printing Sorted Element List ...
7
9
10
12
23
23
34
44
78
101
Bubble Sort
输出:
Printing Sorted Element List ...
7
9
10
12
23
23
34
44
78
101