I can't figure out why this code isn't quite correct. It sorts most of the array, but some numbers are out of place. Any help would be much appreciated.
int partition(int* an_array, int from, int to)
{
int pivot = an_array[(from + to) / 2];
int left = from;
int right = to;
while(left < right)
{
while(an_array[left] < pivot)
{
left = left + 1;
}//end while loop
while(an_array[right] > pivot)
{
right = right - 1;
}//end while
if(left < right)
{
swap_numbers(an_array[left], an_array[right]);
left = left + 1;
right = right - 1;
}//end if
}//end while loop
return right;
}//end partition function
void quick_sort(int* an_array, int from, int to)
{
if(from >= to) return;
int p = partition(an_array, from, to);
quick_sort(an_array, from, p);
quick_sort(an_array, p + 1, to);
}//end quick_sort
You forget to add:
swap_numbers(an_array[from], an_array[right]);
just before
return right;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.