现在的位置: 首页 > 综合 > 正文

排序算法(一):冒泡排序 Bubble Sort

2012年03月04日 ⁄ 综合 ⁄ 共 1081字 ⁄ 字号 评论关闭

冒泡排序 Bubble Sort ── C++实现

 

代码
 1 #include <iostream>
 2 #include <stdlib.h>
 3 
 4 using namespace std;
 5 
 6 void generate_array(int [], int);
 7 void BubbleSort(int [], int);
 8 void display(int[], int);
 9 void swap(int&int&);
10 
11 int main()
12 {
13     const int size = 24;
14     int array[size];
15     generate_array(array, size);
16     cout << "The input numbers:" << endl;
17     display(array, size);
18     BubbleSort(array, size);
19     cout << "The sorted numbers:" << endl;
20     display(array, size);
21 
22     cout << "Hello world!" << endl;
23     return 0;
24 }
25 
26 void generate_array(int array[], int size)
27 {
28     for(int i=0; i!=size; ++i)
29         array[i] = rand()%100;
30 }
31 
32 void BubbleSort(int a[], int n)
33 {
34     for(int i=1; i!=n; i++)
35         for(int j=n; j!=i-1--j)
36             if(a[j] < a[j-1])
37                 swap(a[j], a[j-1]);
38 }
39 
40 void display(int a[], int size)
41 {
42     for(int i=0; i!=size; i++)
43         cout << a[i] << " ";
44     cout << endl;
45 }
46 
47 void swap(int &a, int &b)
48 {
49     int temp = a;
50     a = b;
51     b = temp;
52 }

 

抱歉!评论已关闭.