c++ recursive quicksort infinite loop -


so i've been having problem c++ program quicksorts array of integers. when have more 6 elements in array, sort infinitely loops reason. think i've isolated problem choosing of mm pivotal value, can't work out life of me why it's causing break.

#include<iostream> using namespace std;  int getpivot(int begin,int end){//takes length of array input , returns position of pivot     int len = end-begin;     if(len < 3){         return end;     }else{         return 2;     } };  void quicksort(int begin, int end, int arr[]){     int pivot = arr[getpivot(begin,end)];//get pivotal value - if replace 0 there no problems...     int templeft = begin, tempright = end;     int temp;     while(templeft <= tempright){         while(arr[templeft] < pivot){//find point there 2 elements need swapped             templeft++;         }         while(arr[tempright] > pivot){             tempright--;         }         if(templeft <= tempright){             temp = arr[templeft];//swap elements             arr[templeft] = arr[tempright];             arr[tempright] = temp;             templeft++;//skip these swapped elements in sort             tempright--;         }     }     if (begin < tempright){//only recurse lower if new sub array has length greater 1         quicksort(begin, tempright, arr);     }     if (templeft < end){         quicksort(templeft, end, arr);     } }  main() {     int array[] = {0,1,2,3,4,5,6};     int length = 7;     quicksort(0,length-1,array); } 

you ask why have such weird way of choosing pivotal value, lets instance pivotal value has third element in each sublist or if sub list smaller 3 last item in sublist.

the reason think problem associated pivotal value because when replace method of choosing pivot using first element in sublist don't have problems.

if run, program, segfault after looping infinitely if array being sorted 1 element shorter, work fine. has had me baffled hours now, , can't work out problem is. if has tips or suggestions, appreciated.

quicksort(3,6,arr) call quicksort(3,6,arr).

i think miss

int getpivot(int begin,int end) {     //takes length of array input , returns position of pivot     int len = end-begin;     if(len < 3){         return end;     }else{         return 2+begin; // here     } }; 

edit: clarification

getpivot(3,6) return 2, instead should return index between 3 , 6.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -