算法之冒泡排序

申明:参考    http://www.cnblogs.com/iuices/archive/2011/11/13/2247193.html

原理:将一组数储存在数组List[n]中。逆序,依次比较相邻两个元素的大小,遵循“小数在前,大数在后”的规则交换两数。

        第一次扫描,将最小的数放在数组的第一位置,第二次扫描只要对除去第一位置的其余的数重复上述步骤即可……共扫描n-1次

        程序中引入一个布尔量exchange,在每趟排序开始前,先将其置为FALSE。若排序过程中发生了交换,则将其置为TRUE

      (若在某一趟排序中未发现气泡位置的交换,则说明待排序的无序区中所有气泡均满足轻者在上,重者在下的原则,因此,冒泡排序过程可在此趟排序后终止)

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void BubbleSort(int *list, int n)
 5 {
 6     int i, j, temp;
 7     bool exchange;//交换标志
 8     for (i = 0; i < n-1; i++)
 9     {
10         exchange =false;
11         for (j = n - 2; j >= i; j--)
12         {
13             if (list[j] > list[j + 1])
14             {
15                 temp = list[j];
16                 list[j] = list[j + 1];
17                 list[j + 1] = temp;
18                 exchange = true;
19             }
20             if (!exchange)
21                 return;
22         }
23     }
24 }
25 int main()
26 {
27     int list[10], cnt = 10;
28     cout << "Please enter ten numbers :"<<endl;
29     for (int i = 0; i < 10; i++)
30         cin >> list[i];
31     cout << endl;
32     BubbleSort(list, cnt);
33     for (int i = 0; i < 10; i++)
34         cout << list[i] << " ";
35     cout << endl;
36     return 0;
37 }
原文地址:https://www.cnblogs.com/-rfq/p/5928006.html