/*
* tpop(2): Algorithms and Data Structures
* created on Mar 3, 2011
*/
#include
/* NELEMS macro: computes the number of elements in the array */
#define NELEMS(array) (sizeof(array) / sizeof(array[0]))
void quicksort(int [], int);
void swap(int [], int, int);
/* quicksort main: quick sort an array */
int main(int argc, char *argv[])
{
int i;
int array[] = {1, 3, 5, 7, 9, 2, 6, 4,10,22,8};
/* print the array before sort */
printf("The original array is \n");
for (i = 1; i < NELEMS(array); i++)
printf ("%d ", array[i]);
printf ("\n");
/* print the array after sort */
quicksort(array, NELEMS(array));
printf("The sorted array is \n");
for (i = 1; i < NELEMS(array); i++)
printf ("%d ", array[i]);
printf("\n");
}
/* quicksort: sort v[0]..v[n-1] into increasing order */
void quicksort(int v[], int n)
{
int i, last;
if (n <= 1) /* nothing to do */
return;
swap (v, 0, rand() % n); /* move pivot elem to v[0] */
last = 0;
for (i = 1; i < n; i++) /* partition */
if (v[i] < v[0])
swap(v, ++last, i);
swap(v, 0, last); /* restore pivot */
quicksort(v, last); /* recursively sort */
quicksort(v+last+1, n-last-1); /* each part */
}
/* swap: interchange v[i] and v[j] */
void swap(int v[], int i, int j)
{
int temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
阅读(314) | 评论(0) | 转发(0) |