Site icon DataFlair

Quick Sort in DSA C++

Program 1

// Program for Quick Sort   
#include<stdio.h>
#include<conio.h>
#include<iostream>
#define clrscr() system("cls")
using namespace std;
void quick_sort(int ar[],int l ,int h);  
int main()
{
    clrscr();
    int ar[500],n,low,high;
    int i;
    xyz:cout<<"\nEnter the limit";
    cin>>n;
    if(n>500)
   { 
     cout<<"\n Invalid limit pls enter again";
     goto xyz;
   }
   else
   {
       
       cout<<"\n Enter the elements";
       for(i=0;i<n;i++)
        cin>>ar[i];
        low=0;
        high=n-1;
        quick_sort(ar,low,high);   // low=0 high=9
        cout<<"\n Sorted  elements: \n";
        for(i=0;i<n;i++)
         cout<<ar[i]<<"\n";
   }
  return 0;
}
void quick_sort(int ar[],int l ,int h)   // l=0   h=9
{
       int low,high,key,temp;   
       low=l;         //low=0
       high=h;      //high=9
       key=ar[(low+high)/2];   //pivot
       do
       {
          while(key>ar[low])
          {
               low++;
          }
         while(key<ar[high])
         {
             high--;
         } 
         if(low<=high)
         {
              temp=ar[low];
              ar[low++]=ar[high];
              ar[high--]=temp;
         }
       }while(low<=high);
       if(l<high)
        quick_sort(ar,l,high);
        if(low<=h)
        quick_sort(ar,low,h);
}

 

Exit mobile version