-
-
Save ruanchao/3347667 to your computer and use it in GitHub Desktop.
quick sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//quick sort | |
#include<stdio.h> | |
void quicksort(int*arr,int left, int right); | |
int partition(int *arr,int left,int right); | |
int main() | |
{ | |
int arr[6]={5,4,1,2,8,3}; | |
int i; | |
int n = sizeof(arr)/sizeof(int); | |
quicksort(arr,0,n-1); | |
for(i=0;i<n;i++) | |
printf("%d ",arr[i]); | |
return 0; | |
} | |
void quicksort(int*arr,int left, int right) | |
{ | |
int p; | |
if(left>=right) | |
return; | |
else | |
p = partition(arr,left,right); // partition the array. arr[p] at its correct position | |
quicksort(arr,left,p-1); | |
quicksort(arr,p+1,right); | |
} | |
int partition(int *arr,int left,int right) | |
{ | |
int i=left,j=right-1; | |
int t; | |
int pivot = arr[right]; | |
while(i<=j) | |
{ | |
while(arr[i]<pivot)i++; | |
while(arr[j]>pivot)j--; | |
if(i<=j) | |
{ | |
t = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = t; | |
} | |
else | |
{ | |
t = arr[i]; | |
arr[i] = pivot; | |
arr[right] = t; | |
} | |
} | |
return i; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment