/* 快排的非递归算法 */ /* 使用队列的任务分解方法 */ /* Key : 队列如何快速实现? */ #include <stdio.h> #include <queue.h> typedef struct _TASK_QSORT { int* list; int low; int high; }QsTask; int Partition(int a[], int low, int high) { 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[low] = a[high]; } a[low] = pivot; return low; } void QSort(int a[], int low, int high) { int mid = 0; QsTask firstTask,NxtTsk; firstTask.list = a; firstTask.low = low; firstTask.high = high; queue<QsTask> task; task.push(firstTask); while (!task.empty()) { firstTask = task.front(); mid = Partition(firstTask.list,firstTask.low,firstTask.high); NxtTsk.list = firstTask.list; NxtTsk.low = firstTask.low; NxtTsk.high = mid; task.push(NxtTsk); NxtTsk.low = mid; NxtTsk.high = firstTask.high; task.push(NxtTsk); } } main() { int a[] = {12,98,76,35,22,10}; int i=0; QSort(a,0,5); for (i; i < 6; ++i) { printf("%d/t",a[i]); } printf("/n"); }
老师的堆栈做法
#include "stdio.h" #define N 8 int r[N+1] = { 0,49,38,65,97,76,13,27,49 }; void QuickSort(int *r, int n) { int i,j,rp,top; struct { int left; int right; } stack[100],x,y; x.left=1; x.right=n; top=1; stack[top]=x; while(top>0) { x=stack[top--]; i=x.left; j=x.right; rp=r[i]; while ( i<j ) { while ( i < j && r[j] >= rp ) j--; r[i] = r[j]; while ( i < j && r[i] <= rp) i++; r[j] = r[i]; } r[i] = rp; if ( i < x.right-1) { y.left =i+1; y.right=x.right; stack[++top]=y; } if ( i > x.left+1) { y.right=i-1; y.left =x.left; stack[++top]=y; } } } void main() { int i; QuickSort(r,8); for(i=1;i<=8;i++) printf("%d ",r[i]); printf("/n"); }