排序:C/C++實現插入,選擇,交換,歸併6大排序演算法
阿新 • • 發佈:2020-09-02
最近複習完了第二輪的資料結構,感覺排序這一塊的程式碼很多,平時程式設計就用一個sort()函式草草了事,現在參考資料結構課本把幾個常考的排序演算法編寫出來,方便查閱
#include <iostream> using namespace std; //int n; void show(int a[], int n) { for (int i = 0; i < n; i++) { cout << " " << a[i]; } cout << endl; cout << endl; }void siSort(int a[], int n)//直接插入排序 { int temp,j; for (int i = 1; i < n; i++) { if (a[i] < a[i - 1]) { temp = a[i]; for ( j = i - 1; temp < a[j]; j--) //向後比較,從前往後空位準備插入temp到合適位置 a[j+1] = a[j]; a[j+1] = temp; } } } void biSort(int a[], int n)//折半插入排序 { int temp,j; int low, high,mid; for (int i = 1; i < n; i++) { temp = a[i]; low = 0, high = i - 1; while (low <= high) //二分查詢確定插入位置 { mid = (low + high) / 2; if (temp > a[mid]) low = mid + 1; else high = mid - 1; //cout << "a[i]="<<a[i]<<" i="<<i<<" low=" << low << " " << " high="<<high << endl; } for ( j = i - 1; j>=high+1; j--)//插入temp a[j + 1] = a[j]; a[high + 1] = temp; //cout << endl; } } void bubbleSort(int a[], int n)//氣泡排序 { int temp; for (int j = 0; j < n; j++) { for (int i = n - 1; i >= j; --i) { //cout << "i=" << i << " j=" << j << endl; if (a[i-1] > a[i]) { temp = a[i-1]; a[i-1] = a[i]; a[i] = temp; } } } } void quickSort(int a[], int n,int low,int high)//快速排序 { int temp,i,j; if (low < high) { temp = a[low]; i = low, j = high; while (i < j) { while (i < j && a[j] >= temp) j--; a[i] = a[j]; while (i < j && a[i] <= temp) i++; a[j] = a[i]; } a[i] = temp; quickSort(a, n,low, i - 1); quickSort(a, n,i + 1, high); } } void selectSort(int a[], int n)//簡單選擇排序 { int min = a[0],pos,temp; for (int i = 0; i < n-1; i++) { for (int j = i + 1; j < n; j++) { if (min > a[j]) { min = a[j]; pos = j; } } if (a[i] > min) { temp = a[i]; a[i] = min; a[pos] = temp; } min = a[i + 1]; } //show(a, n); } int* b = (int*)malloc((10+1) * sizeof(int)); void merge(int a[], int n,int low, int mid, int high) { int i, j, k; for (int k = low; k <= high; k++) b[k] = a[k]; for ( i = low, j = mid + 1, k = i; i <= mid && j <= high; k++) { if (b[i] <= b[j]) a[k] = b[i++]; else a[k] = b[j++]; } while (i <= mid) a[k++] = b[i++]; while (j <= high) a[k++] = b[j++]; } void mergeSort(int a[], int n, int low,int high)//歸併排序 { if (low < high) { int mid = (low + high) / 2; mergeSort(a,n, low, mid); mergeSort(a, n, mid + 1, high); merge(a,n, low, mid, high); } } int main(void) { int a[] = { 5,7,4,0,2,6,9,8,3,1 }; int n = sizeof(a) / sizeof(int); //siSort(a, n);//直接插入排序 //biSort(a,n);//折半插入排序 //bubbleSort(a, n);//氣泡排序 //quickSort(a,n, 0, n-1);//快速排序 //selectSort(a, n);//簡單選擇排序 //mergeSort(a,n,0,n-1);//歸併排序 show(a, n); }