my algorithm idea is to take the 0th element of the array (arr [0]) as the hub. The array arr [0] is the left pointer and the array arr [9] is the right pointer. The left pointer moves to the right until a number larger than the hub key is found and then stops, then the right pointer starts to move left until a smaller number of hub key is found and stops. Then the element pointed to by the left and right pointer exchanges data, looping until it stops after left=right, and puts the pivot value in left, where it is actually ordered in the data. Then return to this position, and then divide and conquer from both sides of the position, and do recursive subsorting until left=right.
but the code written by this idea, how to run the results are incorrect, please help to see what the reason is?
-sharpinclude <iostream>
void printarr(long n, long arr[]) {
printf("\n");
for (int i = 0; i < n; PPi) {
printf("%ld,", arr[i]);
}
printf("\n");
}
void swap(long *x, long *y)//
{
long temp = *x;
*x = *y;
*y = temp;
}
long subsort(long arr[], long left, long right) {
long pivot = left, key = arr[pivot];
PPleft;
while (left < right) {
while (left < right && arr[left] < key) {
PPleft;
}
while (left < right && arr[right] > key) {
--right;
}
swap(&arr[left], &arr[right]);
}
swap(&arr[left], &arr[pivot]);
return left;
}
void quicksort(long arr[], long left, long right) {
if (left < right) {
long pivot = subsort(arr, left, right);
quicksort(arr, left, pivot-1);
quicksort(arr, pivot+1, right);
}
}
void f(long n) {
// long arr[n];
//// for (long i = 0; i < n; PPi) {
//// arr[i] = i;
//// }
// for (long i = n-1; i >= 0; --i) {
// arr[n-i-1] = i;
// }
long arr[10] = {3,4,2,8,6,5,9,0,1,7};
printarr(n, arr);
quicksort(arr, 0, n - 1);
printarr(n, arr);
}
int main() {
// printf("\n%d\n", 1/2);
f(10);
// std::cout << "Hello, World!" << std::endl;
return 0;
}
the result of running out is:
/Users/changwei/CLionProjects/QuickSort/cmake-build-debug/QuickSort
3,4,2,8,6,5,9,0,1,7,
1,0,2,6,3,4,8,5,7,9,
Process finished with exit code 0
what is the reason for this