Worse case performance: O(n^2)
Best case performance: O(nlogn)
Average performance: O(nlogn)
#include <iostream>
void quicksort(int arr[],int low,int high);
int partition(int arr[],int low,int high);
using namespace std;
/***********************************/
int partition(int arr[],int low,int high)
{
int pivot,i;
pivot=arr[high];
i=low-1;
for(int j=low; j<high; j++)
{
if(arr[j]<=pivot)
{
i++;
swap(arr[i],arr[j]);
}
}
swap(arr[i+1],arr[high]);
return(i+1);
}
/*********************************/
void quicksort(int arr[],int low, int high)
{
if(low<high)
{
int pivot;
pivot=partition(arr,low,high);
quicksort(arr,low,pivot-1);
quicksort(arr,pivot+1,high);
}
}
/*********************************/
int main()
{
int arr[5]={5,4,3,2,1};
int n=5;
cout << "Before sorting values is: ";
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
quicksort(arr,0,n-1);
cout<<"\n After sorting: ";
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
return 0;
}
0 comments:
Post a Comment