My code is working for arrays such as {11,6,8,23,9,1,5,15} which does not have multiple duplicate values but for array values such as {11,6,8,23,9,1,5,15,7,7,7,7} where I have duplicate values, my code is giving a wrong output. But if I only have two duplicate values, for example 7,7 I am still getting the correct o/p. The real issue begins when I have duplicate values more than 2. I tried debugging in Xcode but since I am a beginner and it's only recently that I started using xcode and started debugging too. I was not able to figure out what the issue was. Also if I make any changes to my code specifically the last if block, somehow my code turns into an infinite loop! Which is very weird. Any help or guidance would be highly appreciated.
Expected o/p: 1,5,6,7,7,7,7,8,9,11,23
o/p that I am getting: 1 5 6 7 7 9 7 7 8 11 15 23
int quicksort(int arr[], int s, int e)
{
int pivot = arr[s];
int count_smaller_than_pivot=0;
//creating a counter to count the elements smaller or equal to the pivot
for(int i =s+1 ; i<=e; i++) {
if (arr[i] <= pivot) {
count_smaller_than_pivot++;
}
}
//to place the pivot at it's correct posiition.
int pivot_index= s+count_smaller_than_pivot;
//swapping the values
int temp = arr[s];
arr[s] = arr[pivot_index];
arr[pivot_index]= temp;
int i=s;
int j=e;
while(i<pivot_index && j>pivot_index) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
// if we find some value which is greater than pivot_index on the left or smaller than pivot_index in the right then we would need to swap
if(i<pivot_index && j>pivot_index) {
int temp2= arr[i];
arr[i] = arr[j];
arr[j] = temp2;
i++;
j--;
}
}
return pivot_index;
}
void recursive_func(int arr[], int s, int e)
{
if (s>=e)
return;
int p = quicksort(arr,s,e);
//sorting the left part
recursive_func(arr,s ,p-1);
//sorting the right part
recursive_func(arr,p+1, e);
}
#include <iostream>
using namespace std;
int main()
{
int n=12;
int arr[12]= {11,6,8,23,9,1,5,15,7,7,7,7};
quicksort(arr, 0, n-1);
recursive_func(arr,0,n-1);
for(int i=0; i<n; i++) {
cout<<arr[i]<<" ";
}
return 0;
}