What I want to do is quick-sort this 12 integer datas {2,3,11,9,12,2,6,15,18,10,7,14}
.
And I should select the pivot 14
which is located in index-11.
The env. of practice is GCC.
#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE 12
void quick_sort(int *list, int left, int right);
int partition(int *list, int left, int right);
void SWAP(int *x, int *y, int *t) { *t = *x; *x = *y; *y = *t; }
/*main start*/
int main() {
//Initialize data[] for sorting
int data[DATA_SIZE] = {2,3,11,9,12,2,6,15,18,10,7,14};
quick_sort(data, 0, DATA_SIZE-1);
for(int i = 0; i < DATA_SIZE; i++) { printf("%d\t",data[i]);}
return 0;
}
/*Main fuction for recursion.*/
void quick_sort(int *list, int left, int right) {
if(left < right) {
//Pivot selection
int q = partition(list, left, right);
//Divide
quick_sort(list, left, q-1);
quick_sort(list, q+1, right);
}
}
/*Devide and Conquere*/
int partition(int *list, int left, int right) {
int pivot; //pivot
int temp; //temporary variable
int low;
int high;
// select
low = left;
high = right+1;
pivot = list[11];
do {
//proceed
do low++; while(list[low]<pivot);
do high--; while(list[high]>pivot);
//pivot-comparison
if(low < high) SWAP(&list[low],&list[high], &temp);
}while(low < high);
//swap after comparison
SWAP(&list[left], &list[high], &temp);
return high;
}
the result is in below.
3 6 2 7 10 9 11 12 14 2 15 18
As result is awkward, so I inserted printf("pivot : %d\n", pivot);
in the partition()
.
pivot : 14
pivot : 7
pivot : 6
pivot : 3
pivot : 11
pivot : 9
pivot : 15
So I fixed the code high = right+1;
in the partition()
to high = right
.
pivot : 14
pivot : 14
pivot : 14
pivot : 14
pivot : 14
pivot : 14
pivot : 14
pivot : 14
pivot : 14
but the sort result is
11 3 12 9 6 2 10 7 18 15 2 14