I started learning algorithm in C++ and stuck with Quicksort. But I'm unable to get the bug in my code that is not sorting the array properly.
Here is the link to code or here is the code:
#include <iostream>
using namespace std;
void printArray(int array[], int len) {
for (int i = 0; i < len; i++) {
cout << array[i] << " ";
}
cout << endl;
}
void swap(int* a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int lo, int hi) {
int pivot = arr[hi];
int i = lo - 1;
for (int j = lo; j < hi-1; j++) {
if (arr[j] <= pivot) {
i +=1;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i+1], &arr[hi]);
return i+1;
}
void quicksort(int arr[], int lo, int hi) {
if (lo < hi) {
int p = partition(arr, lo, hi);
quicksort(arr, lo, p-1 );
printArray(arr, 8);
quicksort(arr, p + 1, hi);
}
}
int main() {
int len;
int array[] = {2,8,7,1,3,5,6,4};
len = (sizeof(array)/sizeof(array[0]));
quicksort(array, 0, len-1);
printArray(array, len);
return 0;
}
I'm printing the array elements so that I can see the behavior of array elements.