简单排序+堆排序

注:所有排序以从小到大排序为例,且函数接口统一定义为:void sortname_sort(int a[], int n)

简单排序:

简单排序有三种:选择排序,冒泡排序,插入排序。其中选择排序非常简单,就是从要排序的数列里找到最小的放在最前面,以此类推,最终完成排序,代码省略。

冒泡排序:

思路是相邻两个元素比较大小如果前面元素大于后面的,则交换位置,最终可以将最大值放在数列最后一个,然后重复上述步骤。

示例代码:

 1 // Bubble sort
 2 #include <iostream>
 3 using namespace std;
 4 void bubble_sort(int a[],int n)
 5 {
 6     for(int i = n-1; i >= 0; i--)
 7     {
 8         for(int j = 0; j < i; j++)
 9         {
10             if(a[j] > a[j+1])
11             {
12                 int tmp = a[j];
13                 a[j] = a[j+1];
14                 a[j+1] = tmp;
15             }
16         }
17     }
18 }
19 
20 int main()
21 {
22     int a[] = {10,2,1,5,4,3,9,7,6,8};
23     const int n = 10;
24     bubble_sort(a,n);
25     for(int i = 0; i < n; i++) cout << a[i] << " ";
26     return 0;
27 }

插入排序:

思路类似于打扑克牌时摸牌整理牌的过程,挑一张最小的放在最左边,再挑一张小的放在左边。

示例代码:

 1 // Insertion sort
 2 #include <iostream>
 3 using namespace std;
 4 void insert_sort(int a[], int n)
 5 {
 6     for(int i = 1; i < n; i++)
 7     {
 8         int tmp0 = a[i], tmp1 = i-1, tmp2 = i;
 9         while(tmp1 >= 0 && a[tmp1] >= tmp0) {a[tmp2] = a[tmp1]; tmp2 = tmp1; tmp1--;} // 选择地方插入的过程
10         a[tmp2] = tmp0; // 找到位置,插入数
11     }
12 }
13 int main()
14 {
15     int a[] = {10,2,1,5,4,3,9,7,6,8};
16     const int n = 10;
17     insert_sort(a,n);
18     for(int i = 0; i < n; i++) cout << a[i] << " ";
19     return 0;
20 }

 

堆排序:

利用小顶堆来排序,代码非常简单。

示例代码

 1 // Heap sort
 2 #include <iostream>
 3 #include <queue> // 注意头文件
 4 using namespace std;
 5 void heap_sort(int a[], int n)
 6 {
 7     int i,j;
 8     priority_queue<int, vector<int>, greater<int> > q; // 建立小顶堆
 9     for(i = 0,j = 0; i < n; i++) q.push(a[i]); // 数据入堆
10     while(!q.empty()) {a[j++] = q.top(); q.pop();} // 出堆
11 }
12 int main()
13 {
14     int a[] = {10,2,1,5,4,3,9,7,6,8};
15     const int n = 10;
16     heap_sort(a,n);
17     for(int i = 0; i < n; i++) cout << a[i] << " ";
18     return 0;
19 }

 

posted @ 2020-08-21 11:32  不敢说的梦  阅读(201)  评论(0)    收藏  举报