快速排序

来源:互联网 发布:最新版itunes软件下载 编辑:程序博客网 时间:2024/06/10 23:30

1、算法介绍(直接百度吧。。。):设要排序的数组是A[0]……A[N-1],首先任意选取一个数据(通常选用数组的第一个数)作为关键数据,然后将所有比它小的数都放到它前面,所有比它大的数都放到它后面,这个过程称为一趟快速排序。值得注意的是,快速排序不是一种稳定的排序算法,也就是说,多个相同的值的相对位置也许会在算法结束时产生变动。对排序数组进行排序,需要经过n趟快速排序,一趟快速排序的算法如下:

1)设置两个变量i、j,排序开始的时候:i=0,j=N-1;
2)以第一个数组元素作为关键数据,赋值给key,即key=A[0];
3)从j开始向前搜索,即由后开始向前搜索(j--),找到第一个小于key的值A[j],将A[j]和A[i]互换;
4)从i开始向后搜索,即由前开始向后搜索(i++),找到第一个大于key的A[i],将A[i]和A[j]互换;
5)重复第3、4步,直到i=j; (3,4步中,没找到符合条件的值,即3中A[j]不小于key,4中A[i]不大于key的时候改变j、i的值,使得j=j-1,i=i+1,直至找到为止。找到符合条件的值,进行交换的时候i, j指针位置不变。另外,i==j这一过程一定正好是i+或j-完成的时候,此时令循环结束,并且此时i和j都指向key的位置,这为下趟快排确定上界和下界提供帮助。
2、算法实现:

#include <iostream>#include <cstdlib>#include <ctime>/* run this program using the console pauser or add your own getch, system("pause") or input loop */void quickSort(int theArray[], int left, int right){if(left >= right)return;int key = theArray[left];int tmp;int i,j;for(i = left,j = right; i!=j;){while(key <= theArray[j] && i != j){j--;}if(key > theArray[j]){tmp = theArray[j];theArray[j] = theArray[i];theArray[i] = tmp;}while(key >= theArray[i] && i != j){i++;}if(key < theArray[i]){tmp = theArray[i];theArray[i] = theArray[j];theArray[j] = tmp;}}int left_1 = left;int right_1 = i-1;             //i == j,且指向key的位置int left_2 = i+1;int right_2 = right;quickSort(theArray, left_1, right_1);quickSort(theArray, left_2, right_2);}void printArray(int theArray[], int n){for(int i = 0; i < n; i++)std::cout << theArray[i] << " ";std::cout << std::endl;}int main(int argc, char *argv[]) {int myArray[30];int length = 30;//int length = sizeof(myArray) / sizeof(myArray[0]);srand(time(NULL));for(int i = 0; i < length; i++){myArray[i] = rand() % 71 + 30;          //30~100中的随机数 }std::cout << "before sort: " << std::endl;printArray(myArray, length);quickSort(myArray, 0, length-1);std::cout << "quick sort: " << std::endl;printArray(myArray, length);return 0;}

3、时间复杂度和空间复杂度

(1)时间复杂度

最好时间复杂度:O(nlogn)

最差时间复杂度:O(n^2)

平均时间复杂度:O(nlogn)

(2)空间复杂度

最好空间复杂度:O(logn)

最差空间复杂度:O(n)

0 0
原创粉丝点击