冒泡排序(高级版)之C++实现

冒泡排序(高级版)之C++实现

一、源代码:BubbleSortHigh.cpp

 1 #include<iostream>
 2 using namespace std;
 3 
 4 /*定义输出一维数组的函数*/
 5 void print(int array[], int n)
 6 {
 7     for (int i = 0; i < n; i++)
 8     {
 9         cout << array[i] << " ";
10     }
11     cout << endl;
12 }
13 
14 /*定义冒泡排序的函数,升序排序,返回交换次数*/
15 int bubbleSort(int array[], int n)
16 {
17     //定义变量,记录交换次数
18     int count = 0;
19     //定义中间变量temp
20     int temp;
21     //遍历数组(进行排序)
22     cout << "开始对数组进行排序了..." << endl;
23     for (int i = 0; i < n; i++)
24     {
25         //定义变量是否进行交换了,默认为未交换,置为0
26         bool swap = false;
27         for (int j = 0; j < n - 1 - i; j++)
28         {
29             cout << "" << (i + 1) << "趟第" << (j + 1) << "次排序" << endl;
30             //如果左边的数大于右边的数就进行交换顺序
31             if (array[j] > array[j + 1])
32             {
33                 temp = array[j];
34                 array[j] = array[j + 1];
35                 array[j + 1] = temp;
36                 cout << array[j] << "" << array[j + 1] << "互换了" << endl;
37                 //输出此时数组的顺序
38                 cout << "数组此时的顺序是:";
39                 print(array, 10);
40                 //每交换一次,记录数加1
41                 count++;
42                 //如果交换了,将swap置为1
43                 swap = true;
44             }
45         }
46         //如果未交换,即swap=0,则进行下一趟
47         if (!swap)
48         {
49             break;
50         }
51     }
52     cout << "数组排序结束了..." << endl;
53     return count;
54 }
55 
56 int main()
57 {
58     //定义待排序的一维数组
59     int array[] = { 1, 3, 4, 5, 2, 6, 10, 9, 8, 7 };
60     //输出原始数组
61     cout << "原始数组是:" << endl;
62     print(array, 10);
63     //对数组进行排序
64     int count = bubbleSort(array, 10);
65     //输出排序后的数组
66     cout << "排序后的数组是:" << endl;
67     print(array, 10);
68     cout << "共交换" << count << "" << endl;
69 }

 

二、运行效果(与初级版运行效果比较,过程更简单)

 

 

posted @ 2017-08-18 17:02  勇闯天涯zfc  阅读(244)  评论(0编辑  收藏  举报