Wednesday, September 26, 2018

Program of Quick Sort in C++


#include<iostream>
using namespace std;

void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}

int partition(int arr[], int start, int end)
{
int pivot = arr[end];
int i,j;

j = start;
for (i = start; i < end; i++)
{
if (arr[i] <= pivot)
{
swap(&arr[i], &arr[j]);
j++;
}

}
swap(&arr[j], &arr[end]);
return j;
}

void quicksort(int arr[], int start, int end)
{
int part;

if (start < end)
{
part = partition(arr, start, end);

quicksort(arr, start, part - 1);
quicksort(arr, part + 1, end);
}
}

int main()
{
int size;
cout<<"\n Enter the size of the array : ";
cin>>size;

int arr[size];

cout<<"\n Enter "<<size<<" elements in the array : ";
for (int i = 0; i < size; i++)
{
cin>>arr[i];
}

quicksort(arr, 0, size - 1);

cout<<"\n Sorted Array : ";
for (int i = 0; i < size; i++)
{
cout<<arr[i]<<" ";
}

return 0;
}


No comments:

Post a Comment