c++ - I am trying to run the following code for quicksort but the output is always a garbage value.What should be the modification in the code? -


this following code

#include<iostream> using namespace std;  int findpivot(int a[],int startindex,int endindex) {     int pivot=a[endindex];     int pivotindex=startindex;     for(int i=0;i<endindex-1;i++)     {         if(a[i]<pivot)         {             int temp=a[i];             a[i]=a[pivotindex];             a[pivotindex]=a[i];             pivotindex++;         }     }      int temp=pivot;//swapping pivot element position.     pivot=a[pivotindex];     a[pivotindex]=temp;     return pivotindex; }  void quicksort(int a[],int startingindex,int endingindex) {     int number;     if(startingindex < endingindex)     {         int returnvalueofpivot= findpivot(a,startingindex,endingindex);         //cout<<returnvalueofpivot<<endl;         quicksort(a,startingindex,returnvalueofpivot-1);//sorting left         quicksort(a,returnvalueofpivot+1,endingindex);//sorting right     } }  int main() {     int number;     cout<<"enter total number of elements"<<endl;     cin>>number;     cout<<"enter values"<<endl;     int a[number-1];     for(int i=0;i<number;i++)     {         cin>>a[i];     }      quicksort(a,0,number-1);      for(int i=0;i<number;i++)     {         cout<<a[i]<<",";     }      return 1; } 

there 3 major problems in code :

  1. int a[number-1]; allocating 1 less space array. note that, array index starts 0. array of 5 numbers

array[5] : array[0],array[1],array[2],array[3],array[4]

  1. swapping array values :
int temp=pivot;//swapping pivot element position. pivot=a[pivotindex]; a[pivotindex]=temp; 

here, swapped pivot value a[pivotindex] not a[endindex]!!

so correct swap have been :

int temp=a[endindex];//swapping pivot element position. a[endindex]=a[pivotindex]; a[pivotindex]=temp; 
  1. for(int i=0;i<endindex-1;i++) incorrect loop

correct loop :

for(int i=startindex;i<=endindex-1;i++)

you need start start index , end till end index. going 0 end - 1. [think of right side array loop, won't start 0]

make these changes , code work.


Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -