1 /*
2 * File: select_bubble_Sort.cpp
3 * ----------------------------
4 * DATE: 20170814
5 *
6 */
7
8 #include <iostream>
9
10 // 交换两个数
11 void swap(int &a, int &b)
12 {
13 int temp;
14 temp = a;
15 a = b;
16 b = temp;
17 }
18
19
20 // 冒泡排序
21 void bubbleSort(int a[], const int length)
22 {
23 for(int i = length-2; i >= 0; i--)
24 {
25 for(int j = 0; j <= i; j++)
26 if(a[j] > a[j+1])
27 swap(a[j], a[j+1]);
28 }
29 }
30
31 // 选择排序
32 void selectSort(int a[], const int length)
33 {
34 int index;
35 for(int i = 0; i < length - 1; i++)
36 {
37 index = i;
38 for(int j = i+1; j < length; j++)
39 if(a[index] > a[j])
40 index = j;
41 swap(a[i], a[index]);
42
43 }
44
45 }
46
47 // 打印显示
48 void displayArray(const int a[], const int length)
49 {
50 for(int i = 0; i < length; i++)
51 std::cout<< a[i] << " ";
52 std::cout<< std::endl;
53 }
54
55 int main(int argc, char *argv[])
56 {
57 int a[] = {6,8,3,0,0,2,9,1};
58 int b[] = {6,8,3,0,0,2,9,1};
59 int length = sizeof(a) / sizeof(a[0]);
60 std::cout<< "排序前:";
61 displayArray(a, length);
62
63 bubbleSort(a, length);
64 std::cout<< "冒泡法:";
65 displayArray(a, length);
66
67 selectSort(b, length);
68 std::cout<< "冒泡法:";
69 displayArray(b, length);
70 return 0;
71 }