Skip to content

Instantly share code, notes, and snippets.

@rohit-nsit08
Created September 2, 2011 18:34
Show Gist options
  • Save rohit-nsit08/1189424 to your computer and use it in GitHub Desktop.
Save rohit-nsit08/1189424 to your computer and use it in GitHub Desktop.
quick sort
//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