Sunday 6 October 2013

Quick Sort code in C++

//Quick Sort Algorithm 
#include<iostream>
using namespace std;
#include<conio.h>
//Function for partitioning the array

int Partition(int low,int high,int arr[])
{
     int i,high_var=high,low_var=low,pivot,temp;
     pivot=arr[low];
     while(low<high)
     {
                    while(arr[low_var]<pivot)
                    {
                                   low_var++;
                    }
                    while(arr[high_var]>pivot)
                    {
                                   high_var--;
                    }
                    if(low_var<high_var)
                    {
                                temp=arr[low_var];
                                arr[low_var]=arr[high_var];
                                arr[high_var]=temp;
                    }
                    else
                    {
                        temp=pivot;
                        pivot=arr[low_var];
                        arr[low_var]=temp;
                        break;
                    }
     }
     return high_var;    
}
void Quick_sort(int low,int high,int arr[])
{
  int Piv_index,i;
  if(low<high)
  {
          Piv_index=Partition(low,high,arr);
          Quick_sort(low,Piv_index-1,arr);
          Quick_sort(Piv_index+1,high,arr);
  }
}
int main()
{
      int a[100],n,low,high,i;
      cout<<"Enter number of elements:";
      cin>>n;
      //a=new int[n];
      cout<<"enter the elements:";
      for(i=0;i<n;i++)
      cin>>a[i];
      //for(i=0;i<n;i++)
      //a[i]=rand()%100;
      cout<<"\nInitial Order of elements:\n";
      for(i=0;i<n;i++)
      {
                      cout<<a[i]<<"\t";
      }   
      high=n-1;
      low=0;
      Quick_sort(low,high,a);
      cout<<"\nFinal Array After Sorting:\n";
      for(i=0;i<n;i++)
      {
                cout<<a[i]<<"\t";
      }
      _getch();
      return 0;
}

No comments:

Post a Comment