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 :
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]
- 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;
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
Post a Comment