(1)快速排序(非递归)
[code]
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define ARRAY_SIZE 1024
#define STACK_SIZE 1024
struct stackNode
{
short from, to;
}Stack[STACK_SIZE];
int main()
{
int iDat[ARRAY_SIZE];
int iCursor, iTop;
srand ((unsigned) time (NULL));
for (iCursor = 0; iCursor < 1024; ++ iCursor) iDat[iCursor] = rand ();
Stack[0].from = 0, Stack[0].to = 1023; iTop = 0;
stackNode sn;
for ( ; iTop >= 0; ) {
sn = Stack[iTop];
--iTop;
short l = sn.from, r = sn.to;
int pivot = iDat[l];
while (l < r) {
while (l < r && iDat[r] >= pivot) --r;
iDat[l] = iDat[r];
while (l < r && iDat[l] <= pivot) ++l;
iDat[r] = iDat[l];
}
iDat[l] = pivot;
if (sn.from < l - 1) { Stack[++iTop].from = sn.from; Stack[iTop].to = l-1; }
if (sn.to > l + 1) { Stack[++iTop].from = l+1; Stack[iTop].to = sn.to; }
}
for (iCursor = 0; iCursor < 1024; ++ iCursor) printf ("%d ", iDat[iCursor]);
printf ("/n");
return 0;
}
[/code]
堆排序:
[code]
void heapAdjust(int a[], int le, int hi)
{
int top = a[le];
for (int p = 2*le + 1; p <= hi; p = p*2+1) {
if (p < hi && a[p+1] > a[p]) ++p; // right child is larger.
if (a[p] <= top) break; // p is the position to lay value of 'top'.
a[le] = a[p]; le = p;
}
a[le] = top;
}
bool heapSort(int dat[], int n)
{
int i, ch;
if (n <= 1) return true;
for (i = (n-1) / 2; i >= 0; --i) {
heapAdjust(dat, i, n-1);
}
for (i = 1; i < n; ++i) {
int t = dat[0]; dat[0] = dat[n-i]; dat[n-i] = t;
heapAdjust(dat, 0, n-i-1);
}
return true;
}
[/code]