快速排序

来源:互联网 发布:超人 知乎 编辑:程序博客网 时间:2024/04/18 09:46

无聊练习下快排:

非递归版(从大到小):

#include <iostream>#include <cstdio>#include <ctime>#include <cstdlib>using namespace std;int Stack[1024],top;int solve(int *arr, int st, int ed){    int tem = arr[st];    while(st < ed)    {        while(st < ed && arr[ed] <= tem)            ed --;        arr[st] = arr[ed];        while(st < ed && arr[st] >= tem)            st ++;        arr[ed] = arr[st];    }    arr[st] = tem;    return st;}void QuickSort(int *arr, int st, int ed){    if(st < ed)    {        int mid = solve(arr,st,ed);        if(st < mid-1)        {            Stack[++top] = st;            Stack[++top] = ed;        }        if(mid+1 < ed)        {            Stack[++top] = mid+1;            Stack[++top] = ed;        }        while(top)        {            int high = Stack[top--];            int low = Stack[top--];            mid = solve(arr,low,high);            if(low < mid-1)            {                Stack[++top] = low;                Stack[++top] = mid-1;            }            if(mid + 1 < high)            {                Stack[++top] = mid+1;                Stack[++top] = high;            }        }    }}int main(){    int *array;    int len;    while(cin >> len)    {        array = new int [len+1];        top = 0;        srand((int)time(0));        for(int i=1; i<=len; i++)            array[i] = rand()%1024 + 1;        int startTime = clock();        QuickSort(array,1,len);        int endTime = clock();        printf("Sort Time: %d\n",endTime-startTime);        for(int i=1; i<=len; i++)            printf("%d ",array[i]);        puts("");        delete [] array;        array = NULL;    }    return 0;}

 

递归版(从小到大):

void QuickSort(int *arr, int st, int ed){    if(st < ed)    {        int low = st, high = ed;        int tem = arr[st];        while(low < high)        {            while(low < high && arr[high] >= tem)                high --;            arr[low] = arr[high];            while(low < high && arr[low] <= tem)                low ++;            arr[high] = arr[low];        }        arr[low] = tem;        QuickSort(arr,st,low-1);        QuickSort(arr,low+1,ed);    }}


 

原创粉丝点击