首页 > 代码库 > 基础算法 快速排序

基础算法 快速排序

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #define N 6
 4 int partition(int arr[], int low, int high){
 5     int key;
 6     key = arr[low];
 7     while(low<high){
 8         while(low <high && arr[high]>= key )
 9             high--;
10         if(low<high)
11             arr[low++] = arr[high];
12         while( low<high && arr[low]<=key )
13             low++;
14         if(low<high)
15             arr[high--] = arr[low];
16     }
17     arr[low] = key;
18     return low;
19 }
20 void quick_sort(int arr[], int start, int end){
21     int pos;
22     if (start<end){
23         pos = partition(arr, start, end);
24         quick_sort(arr,start,pos-1);
25         quick_sort(arr,pos+1,end);
26     }
27     return;
28 }
29 
30 int main(void){
31     int i;
32     int arr[N]={32,12,7, 78, 23,45};
33     printf("before\n");
34     for(i=0;i<N;i++)
35         printf("%d\t",arr[i]);
36     quick_sort(arr,0,N-1);
37     printf("\nafter\n");
38     for(i=0; i<N; i++)
39         printf("%d\t", arr[i]);
40     printf ("\n");
41     return 0;
42 }

 

基础算法 快速排序