Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

quick sort c++

#include<iostream>
using namespace std;

void swap(int j , int k)
{
    int temp;
    temp = j;
    j = k;
    k = temp;
}

int partition(int arr[] , int s , int e)
{
  
   
   int  pivot = arr[e]; // last element as pivot
    int pindex = s; // initially 0
    for(int i=s ; i<e; i++)
    {
           if(arr[i]<pivot)
           {
            int temp = arr[i];
          arr[i] = arr[pindex];
         arr[pindex] = temp;
            pindex++;
           }
    }

    int temp = arr[e];
    arr[e] = arr[pindex];
      arr[pindex] = temp;
    return pindex;

}

void QuickSort(int arr[] , int s , int e  )
{
    if(s<e)
    {
       int  p = partition(arr , s , e );
        QuickSort(arr , s , (p-1)  ) ;
        QuickSort(arr , (p+1) , e );
    }
}

 int main()
 {
    int i,n;
    cout<<" enter the number of elements in the array :"<<endl;
    cin>>n;

     int a[n];

    cout<<" enter the elements of the array :"<<endl; 

     for(i=0; i<n; i++)
     {
        cin>>a[i];
     }


     QuickSort(a , 0 , n-1);

     cout<< " sorted array :"<<endl;

     for(i=0; i<n; i++)
     {
        cout<<a[i]<<endl;
     }
    
    return 0;
 }
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #quick #sort
ADD COMMENT
Topic
Name
8+9 =