C++ code for quick sort


C++ code for quick sort

This is C++ example code for the quick sort.

#include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;

int partition(int A[], int start, int end){

  int pivot,pindex, l,r;
  pindex=(start+end)/2; //index of pivot
  swap(A[end],A[pindex]); //move pivot to the end of list
  pivot=A[end];

  l=start;
  r=end-1;
  while(l<=r){
    while(A[l]<pivot){l++;} //skip value less than pivot
    while(A[r]>pivot){r--;} //skip value greater than pivot
    if(l<=r) {swap(A[l],A[r]);} //swapping

}

  swap(A[end],A[l]); //swap pivot and the value at index l
  return l;
}



void quicksort(int A[], int start, int end){
  int q;
  while(start<end){
  q=partition(A,start,end);
  if(start<q){ //sort the left sub-list
     quicksort(A,start,q-1);
     start++;
     }
  else{ //sort the right sub-list
    quicksort(A, q+1, end);
    end--;
     }
   }
}



int main(int argc, char *argv[])

{

  int a[]={70,30,90,20,11,1,4,0}; //before sort array
  quicksort(a,0,8); //sort the arry
  for(int i=0;i<8;i++) //after sorting
    cout<<a[i]<<"\t";

getch();
return 0;

}



Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.