/************************************* 快速排序: 把a[]中的元素快速排序,最小座标low,最大座标high *****************************************/ void quik_sort(int *a, int low, int high) { int i = low; int j = high; int temp = a[i]; if( low < high) { while(i < j) { while( (a[j] >= temp) && (i < j) ) { j--; } a[i] = a[j]; while( (a[i] <= temp) && (i < j) ) { i++; } a[j]= a[i]; } a[i] = temp; quik_sort(a, low, i - 1); quik_sort(a, j+1, high); } else { return; } }
void sort_array(int * array, int lenght) { if (lenght <= 0 || !array) { return; } quik_sort(array, 0, lenght); }
void quik_sort(int * array, int begin_pos, int end_pos) { //printf("Begin pos: %d; End pos: %d\n", begin_pos, end_pos); if (begin_pos == end_pos || begin_pos < 0 || end_pos < 0) { return; } int base_index = begin_pos; //index of arbitrary element //swap first and last elements of subarray to use last as arbitrary int temp = array[end_pos - 1]; array[end_pos - 1] = array[begin_pos]; array[begin_pos] = temp; //printf("Arbitrary: %d\n", array[begin_pos]); for (int i = begin_pos + 1; i < end_pos; ++i) { //printf("%d ", array[i]); if (array[base_index] > array[i]) { if (base_index + 1 < i) { int temp = array[base_index + 1]; array[base_index + 1] = array[i]; array[i] = temp; } int temp = array[base_index]; array[base_index] = array[base_index + 1]; array[base_index + 1] = temp; ++base_index; } //printf("\n"); } if (base_index != begin_pos) { //printf("before new iteration. Base index: %d. begin_pos: %d\n", base_index, begin_pos); quik_sort(array, begin_pos, base_index); } if (base_index != end_pos - 1) { //printf("before new iteration. Base index: %d. end_pos - 1: %d\n", base_index, end_pos - 1); quik_sort(array, base_index + 1, end_pos); } }