Pages

Monday, 8 November 2021

Program to illustrate Quick sort in c++

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
class quicksort
{
    public:
int i,n;
int arr[10];
    public:
void getarray();
int partition(int * ,int ,int);
void sortit(int *, int , int);
void display();
};

void quicksort::getarray()
{
    cout<<"Enter Array size: ";
    cin>>n;
    cout<<"unsorted array: ";
    for(int i=0;i<n;i++){
cin>>arr[i];
    }
}

void quicksort::sortit(int *arr, int p, int r)
{
   if (p < r)
{
    int q=partition(arr, p, r);
    sortit(arr, p, q-1);
    sortit(arr, q+1, r);
}
}

int quicksort::partition(int *arr, int p, int r)
{
   int pivot = arr[r];
   int i = (p-1); // index of smaller element
   for (int j=p; j<=r-1; j++)
   {
   // If current element is smaller than the pivot
    if (arr[j] < pivot)
       {
i++;
// swap a[i] and a[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
       }
    }
    // swap a[i+1] and a[r] (or pivot)
    int temp = arr[i+1];
    arr[i+1] = arr[r];
    arr[r] = temp;
    cout<<"\n\n exchange"<<setw(5)<<arr[r]<<setw(5)<<" and"<< arr[i+1];
    return i+1;
}

void quicksort::display()
{
    cout<<"\n The sorted element :";
    for(int i = 0 ; i < n; i++){
cout<<arr[i]<<" ";
    }
}
void main()
{
    clrscr();
    quicksort qs;
    qs.getarray();
    qs.sortit(qs.arr,0,qs.n-1);
    qs.partition(qs.arr,0,qs.n-1);
    qs.display();
    getch();
}

output:
1.Example : 2 8 6 1 4 3 


2.Example: 10 80 30 90 40 50 70


Quick sort animation video link:
https://www.youtube.com/watch?v=PgBzjlCcFvc&t=109s

No comments:

Post a Comment

Constructors & Destructors in c++

  Constructors :  A Constructor is a special member function, which is used to initialize the objects of its class. The Constructor is invok...