几种排序的优质写法

 1 // 插入排序的写法:即使不需要哨兵,也可以写的很流畅。 
 2 int* insertionSort(int* A, int n) {
 3         // write code here
 4         for(int i=1;i<n;i++){
 5             int j=i-1,tmp=A[i];
 6             while(j>=0 && A[j]>tmp){
 7                 swap(A[j],A[j+1]);
 8                 j--; //在while循环中一定注意变量控制
 9             }
10         }
11         return A;
12 }
 1 // 归并排序的不错写法
 2 void merge(int*,int,int,int);
 3 
 4 // mergeSort:递归;
 5 // 提供参数[left,right)
 6 void mergeSort(int* A,int left,int right) {
 7     if(right-left>1){
 8         mergeSort(A,left,(left+right+1)/2);
 9         mergeSort(A,(left+right+1)/2,right);  // (left+right+1)/2 : 一定要+1; (因为整数除法的机制)
10         merge(A,left,(left+right+1)/2,right);
11     }
12 }
13 
14 // [left,mid) , [mid,right);
15 // 对于[left,right)的二分有序段进行整合.   倒序进行插入
16 // 学会使用标准库!(vector!!!)
17 void merge(int* A,int left,int mid,int right){
18     vector<int> p;
19     copy(A+mid,A+right,back_inserter(p));  // 一定要使用插入迭代器,另外对于vector只能使用back_inserter,不能使用front_inserter,因为vector不支持push_front.
20 
21     // 倒序插入
22     int i=mid-1,j=p.size()-1,index=right-1;
23     while(i>=left && j>=0){
24         if(A[i]<=p[j]){
25             A[index]=p[j--];
26         }
27         else{
28             A[index]=A[i--];
29         }
30         index--;
31     }
32 }
 1 // 快排:思想到位 (关键:right所在的位置是最终位置) 
 2 // [left,right)
 3 void QuickSort(int *A,int left,int right){
 4     if(right-left>1){
 5         int i=left+1,j=right-1;
 6         while(i<=j){
 7             while(i<=j && A[i]<=A[left]){
 8                 i++;
 9             }
10             while(i<=j && A[j]>=A[left]){
11                 j--;
12             }
13             if(i>j){
14                 swap(A[left],A[j]);
15                 break;
16             }
17             swap(A[i],A[j]);
18         }
19         QuickSort(A,left,j);
20         QuickSort(A,j+1,right);
21     }
22 }
原文地址:https://www.cnblogs.com/yy-1046741080/p/12350636.html