1.快速排序:是對冒泡排序的一種改進(jìn),其基本思想是選取一個記錄作為樞軸,經(jīng)過一趟排序,將整段序列劃分為兩個部分,其中一部分的值都小于樞軸,另一部分都大于樞軸,然后繼續(xù)對這兩部分進(jìn)行排序,從而使整個序列達(dá)到有序。
1)我們從待排序的記錄序列中選取一個記錄(通常第一個)作為基準(zhǔn)元素(稱為key)key=arr[left],然后設(shè)置兩個變量,left指向數(shù)列的最左部,right指向數(shù)據(jù)的最右部。
2)?key首先與arr[right]進(jìn)行比較,如果arr[right]<key,則arr[left]=arr[right]將這個比key小的數(shù)放到左邊去,如果arr[right]>key則我們只需要將right--,right--之后,再拿arr[right]與key進(jìn)行比較,直到arr[right]<key交換元素為止。
(3)??如果右邊存在arr[right]<key的情況,將arr[left]=arr[right],接下來,將轉(zhuǎn)向left端,拿arr[left ]與key進(jìn)行比較,如果arr[left]>key,則將arr[right]=arr[left],如果arr[left]<key,則只需要將left ,然后再進(jìn)行arr[left]與key的比較。
(4)??然后再移動right重復(fù)上述步驟
(5)??最后得到 {18 11 0 8} 23 {46},再對左子數(shù)列與右子數(shù)列進(jìn)行同樣的操作。最終得到一個有序的數(shù)列。
//快速排序:#include<stdio.h>//遞歸實現(xiàn):void quicksort(int *arr, int low, int high){ int i, j, m, tmp; tmp = arr[low]; if (low < high) { //Swap(s[l], s[(l r) / 2]); //將中間的這個數(shù)和第一個數(shù)交換 參見注1 int i = low, j = high, x = arr[low]; while (i < j) { while (i < j && arr[j] >= x) // 從右向左找第一個小于x的數(shù) j--; if (i < j) arr[i ] = arr[j]; while (i < j && arr[i] < x) // 從左向右找第一個大于等于x的數(shù) i ; if (i < j) arr[j--] = arr[i]; } arr[i] = tmp; quicksort(arr, low, i - 1); // 遞歸調(diào)用 quicksort(arr, i 1, high); }}int main(){ int arr[] = { 2, 5, 6, 8, 12, 7, 16, 11 }; int len = sizeof(arr) / sizeof(int); quicksort(arr,0,7); for (int i = 0; i < len; i ) { printf("%d ", arr[i]); } printf("\n"); return 0;}//非遞歸//劃分算法int Partition(int a[], int low, int high){ //假設(shè)每次都以第一個元素作為樞軸值,進(jìn)行一趟劃分: int pivot = a[low]; while (low<high) { while (low<high && a[high] >= pivot) --high; a[low] = a[high]; //停下來做交換 while (low<high && a[low] <= pivot) low; a[high] = a[low]; //停下來做交換 } a[low] = pivot; //pivot的最終落點 return low;}void QuickSort(int a[], int left, int right){ //手動利用棧來存儲每次分塊快排的起始點 //棧非空時循環(huán)獲取中軸入棧 stack<int> s; if (left < right) { int boundary = Partition(a, left, right); if (boundary - 1 > left) //確保左分區(qū)存在 { //將左分區(qū)端點入棧 s.push(left); s.push(boundary - 1); } if (boundary 1 < right) //確保右分區(qū)存在 { s.push(boundary 1); s.push(right); } while (!s.empty()) { //得到某分區(qū)的左右邊界 int r = s.top(); s.pop(); int l = s.top(); s.pop(); boundary = Partition(a, l, r); if (boundary - 1 > l) //確保左分區(qū)存在 { //將左分區(qū)端點入棧 s.push(l); s.push(boundary - 1); } if (boundary 1 < r) //確保右分區(qū)存在 { s.push(boundary 1); s.push(r); } } }}int main(){ int arr[] = { 2, 5, 6, 8, 12, 7, 16, 11 }; int len = sizeof(arr) / sizeof(int); QuickSort(arr,0,7); for (int i = 0; i < len; i ) { printf("%d ", arr[i]); } printf("\n"); return 0;}
歸并排序:
來源:https://www.icode9.com/content-1-442801.html