c++ - Quicksort implementation error -


i trying implement quicksort. control seems never exiting quicksort function. appreciated.

a few pointers:

  1. i using first element pivot. know better , efficient techniques exist choose pivot, not that.

2.the 'k' variable in partition function pivot element.

as far know, problem partition function, since have tried debugging various times.

also, not homework question. trying implement algorithm after having learnt myself.

#include<iostream> using namespace std;  void swap(int *a,int *b) {     int temp;     temp=*a;     *a=*b;     *b=temp; }  void readarray( int a[],int n) {     cout<<"enter elements array\n";     for(int i=0;i<n;i++)         cin>>a[i]; }  void printarray(int a[],int n) {     cout<<"elements follows\n";     for(int i=0;i<n;i++)         cout<<a[i]<<" ";      cout<<endl; }   int partition(int low,int high,int a[]) {     int i,j,k;     i=low;     j=high;     k=low;      while(i<=j)     {         while(a[i]<a[k])             i++;          while(a[j]>=a[k])             j--;           if(i<=j)         {             swap(a[i],a[j]);             i++;             j--;         }     }      if(i>j)         swap(a[k],a[j]);      return j; }  void quicksort(int low,int high,int a[]) {     int k;     if(low<high)     {         k=partition(low,high,a);         quicksort(low,k-1,a);         quicksort(k+1,high,a);     } }  int main() {     int a[20];     int n;     cout<<"enter size of array\n";     cin>>n;     readarray(a,n);     cout<<"before sorting\n";     printarray(a,n);      quicksort(0,n,a);      cout<<"after sorting contents are\n";      printarray(a,n);      return 0; } 

in main function have tried using both quicksort(0,n,a) , quicksort(0,n-1,a). neither worked.

there problem partition routine, see comments:

int partition( int low, int high,int a[]) {    int i, j, k;    = low;     j = high;    k = low;    while ( < j )  {   while( a[i] <= a[k] ) // move while item < kth element    i++;   while( a[j] > a[k] ) // move j while item > kth element    j--;   if ( < j )    swap(&a[i],&a[j]); //pass address of elements  }  swap(&a[low],&a[j]); // j final position kth element (viz.the pivot )     return j; } 

call quick sort routine using:

quicksort(0,n-1,a);


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -