常用排序算法

1. 冒泡排序

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <stdlib.h>
 4 using namespace std;
 5 
 6 void bubble_sort(int a[], int n)
 7 {
 8     for (int i = 1; i < n; i++)
 9     {
10         bool flag = true;
11         for (int j = 0; j < n - i; j++)
12         {
13             if (a[j] > a[j+1])
14                 swap(a[j], a[j+1]);
15             flag = false;
16         }
17         if (flag == false)
18             break;
19     }
20 }
21 
22 int main(void)
23 {
24     int a[] ={5,4,9,5,2,7};
25     bubble_sort(a, 6);
26     for (int i = 0; i < 6; i++)
27     {
28         cout<<a[i]<<endl;
29     }
30     system("pause");
31 }

 

2. 选择排序

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <stdlib.h>
 4 using namespace std;
 5 
 6 void select_sort(int a[], int n)
 7 {
 8     for (int i =0; i < n; i++)
 9     {
10         int min_index = i;
11         for(int j = i + 1; j < n; j++)
12         {
13             if (a[j] < a[min_index])
14                 min_index = j;
15         }
16         swap(a[i], a[min_index]);
17     }
18 }
19 
20 int main(void)
21 {
22     int a[] ={5,4,9,5,2,7};
23     select_sort(a, 6);
24     for (int i = 0; i < 6; i++)
25     {
26         cout<<a[i]<<endl;
27     }
28     system("pause");
29 }

3. 快速排序

 

 

4. 归并排序

 

posted on 2016-03-31 22:05  lz亢龙有悔  阅读(188)  评论(0编辑  收藏  举报

导航