You can select the s randomly. This way may avoid the worst case.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10
#define SWAP(x,y) {int t; t = x; x = y; y = t;}
int partition(int number[], int left, int right) {
int i, j, s;
s = number[right];
i = left - 1;
for(j = left; j < right; j++) {
if(number[j] <= s) {
i++;
SWAP(number[i], number[j]);
}
}
SWAP(number[i+1], number[right]);
return i+1;
}
void quicksort(int number[], int left, int right) {
int q;
if(left < right) {
q = partition(number, left, right);
quicksort(number, left, q-1);
quicksort(number, q+1, right);
}
}
int main(void) {
int number[MAX] = {0};
int i, num;
srand(time(NULL));
printf("Before Sort:");
for(i = 0; i < MAX; i++) {
number[i] = rand() % 100;
printf("%d ", number[i]);
}
quicksort(number, 0, MAX-1);
printf("\nAfter Sort:");
for(i = 0; i < MAX; i++)
printf("%d ", number[i]);
printf("\n");
printf("Press any key to end...\n");
getchar();
return 0;
}
沒有留言:
張貼留言