快速排序
来源:互联网 发布:mac能下sai吗 编辑:程序博客网 时间:2024/06/05 19:00
快速排序算法也是基于分治策略的。首先把原数组分解成两个子数组(可能空)A[p,q-1]和A[q+1,r];其中A[p,q-1]里边的元素都小于等于A[q],A[q+1]里边的元素都大于A[q];下标q也在这个分隔中进行计算。
然后,通过递归调用快速排序,对子数组A[p,q-1]和A[q+1,r]进行排序。
最后合并两个子数组的排序结果,因为两个子数组是就地排序的,将他们的合并不需要操作,整个数组A[p,..r]已排序。
#include <iostream>#include <stdlib.h>#include <time.h>using namespace std;void Swap(int* A, int lIndex, int rIndex);void QuickSort(int *A, int startIndex, int endIndex);int Partition(int * A, int startIndex, int endIndex);int RandomizedPartition(int*A, int startIndex, int endIndex);int main (){ int arr[] = {3,1,5,2,4,99,8,7}; int len = sizeof(arr)/sizeof(arr[0]); QuickSort(arr, 0, len-1); for (int i = 0; i < len; ++i) { cout << arr[i] << "\t"; } cout << endl; return 0;}void QuickSort(int *A, int startIndex, int endIndex){ if (startIndex < endIndex) { // 末尾分离 //int partitionIndex = Partition(A, startIndex, endIndex); //随机分离 int partitionIndex = RandomizedPartition(A, startIndex, endIndex); QuickSort(A,startIndex, partitionIndex-1); QuickSort(A, partitionIndex+1, endIndex); }}int Partition(int * A, int startIndex, int endIndex){ int key = A[endIndex]; int recursiveIndex = startIndex-1; for (int i = startIndex; i < endIndex; ++i) { if (A[i] <= key) { recursiveIndex += 1; Swap(A,recursiveIndex,i); } } Swap(A, recursiveIndex+1, endIndex); return recursiveIndex+1;}int RandomizedPartition(int*A, int startIndex, int endIndex){ int i = (rand() % (endIndex - startIndex + 1)) + startIndex; Swap(A,i,endIndex); return Partition(A,startIndex, endIndex);}void Swap(int* A, int lIndex, int rIndex){ int tmp = A[lIndex]; A[lIndex] = A[rIndex]; A[rIndex] = tmp;}
方法2:默认取当前数组的第一个元素作为键值,然后从后向前找一个比这个元素小的值并记录索引为high,并替换;然后从前往后找一个比这个元素大的值记录索引为low,并替换;……直到low == high,一趟结束,此刻键值左边的元素比其小,键值右边的元素比其大。然后多左右两部分元素重复此过程
void QuickSort (int* pArr, int low, int high){ if (pArr == NULL || low >= high) { return; } int i = low, j = high; int key = pArr[i]; while (i < j) { //从后向前找一个比它小的 while (pArr[j] >= key && i < j) { --j; } if (i < j) { pArr[i] = pArr[j]; } //从前向后,找一个比它大的 while (pArr[i] <= key && i < j) { ++i; } if (i < j) { pArr[j] = pArr[i]; } } pArr[i] = key; QuickSort (pArr, low, i-1); QuickSort (pArr, i+1, high);}
0 0