【程序】排序(直接法与冒泡法)

 1 #include<iostream>
 2 using namespace std;
 3 
 4 int findSmallest(int array[], int i,int j);
 5 void sort(int array[],int i);
 6 void swap(int array[], int i,int j);
 7 void displayArray(int array[], int i);
 8 
 9 const int SIZE = 6;
10 
11 int main()
12 {
13     int array[SIZE];
14     for (int i = 0;i < SIZE;i++)
15     {
16         cout << "enter value:";
17         cin >> array[i];
18     }
19     cout << "original array:   ";
20     displayArray(array,SIZE);                               //展示输入的数据
21 
22     sort(array,SIZE);                                       //排序
23 
24     cout << "sorted array:   ";
25     displayArray(array, SIZE);
26 
27     cin.ignore();
28     cin.get();
29     return 0;
30 }
31 //***************************************************
32 void displayArray(int array[], int SIZE)
33 {
34     for (int i = 0;i < SIZE;i++)
35     {
36         cout << array[i] << " ";
37     }
38     cout << endl;
39 }
40 //***************************************************
41 void sort(int array[], int SIZE)
42 {
43     for (int i = 0;i<SIZE;i++)                                //遍历数组的序号
44     {
45         int index = findSmallest(array,i,SIZE);
46         swap(array,i,index);                                   //此处的i代表当前进行到的数组号
47     }
48 }
49 
50 //***************************************************
51 //查找最小的数组元素序号
52 int findSmallest(int array[], int currentOne,int size)
53 {
54     int smallest = currentOne;
55     for (int i=currentOne+1;i<size;i++)
56     {
57         if (array[i]<array[smallest])
58         {
59             smallest = i;
60         }
61         
62     }
63     //return 0;
64     return smallest;
65 }
66 
67 //***************************************************
68 //实现互换次序
69 void swap(int array[], int current, int indexSmall)
70 {
71     int temp = array[current];
72     array[current] = array[indexSmall];
73     array[indexSmall] = temp;
74 }

贯彻“算法+化整为零”,逐步调试

占位符的问题:void----------return;

int---------return0;

bool------return true/false;

程序运行结果:

enter value:4
enter value:33
enter value:556
enter value:26
enter value:212
enter value:55
original array: 4 33 556 26 212 55
sorted array: 4 26 33 55 212 556

冒泡法:

 1 //冒泡法排序
 2 #include <iostream>
 3 #include <iomanip>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int a[] = { 4 ,33, 556, 26, 212, 55,0 };
 9     int i, j, tmp;
10     bool flag;//记录一趟起泡中有没有发生过交换
11 
12     for (i = 1;i < 7;++i)//控制总的起泡过程
13     {
14         flag = false;
15         for(j=0;j<7-i;++j)//一次起泡
16             if (a[j + 1] < a[j])
17             {
18                 tmp = a[j];
19                 a[j] = a[j + 1];
20                 a[j + 1] = tmp;
21                 flag = true;
22             }
23         if (!flag) break;
24     }
25 
26     cout << endl;
27     for (i = 0;i < 7;++i)
28         cout << a[i] << " ";
29 
30     cin.get();
31     return 0;
32 }


0 4 26 33 55 212 556

原文地址:https://www.cnblogs.com/skylover/p/7054029.html