由快速排序的衍生.web
#include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX 30 int arr[MAX]; void quickSort(int arr[], int start, int end, int top); int getIndex(int arr[], int start, int end); int main(){ srand(time(0)); for(int i = 0; i < MAX; ++i){ arr[i] = rand()%100; printf("%d ", arr[i]); } putchar('\n'); int top; scanf("%d", &top); quickSort(arr, 0, MAX-1, top); for(int i = 0; i < MAX; ++i){ printf("%d ", arr[i]); } return 0; } void quickSort(int arr[], int start, int end, int top){ if(start < end){ int index = getIndex(arr, start, end); if( index == top ){ return; }else if( index > top ){ quickSort(arr, start, index-1, top); }else if( index > top ){ quickSort(arr, index+1, end, top); } } } int getIndex(int arr[], int start, int end){ int key = arr[start]; while(start < end){ // 在队尾找到比Key值小的元素, while(start < end && key <= arr[end]){ end--; } arr[start] = arr[end]; // 在队头找到比Key值大的元素 while(start < end && key >= arr[start]){ start++; } arr[end] = arr[start]; } // start 与 end 相等, arr[start] = key; return start; }