hi everyone this is my code below
#include <iostream>
using namespace std;
void printArray(int arr[],int size){
cout<<"[ ";
for(int i = 0;i<size;++i){
cout<<arr[i]<<", ";
}
cout<<"\b\b ]\n";
}
void swap(int &a,int &b){
a^=b^=a^=b;
}
void bubbleSort(int arr[],int n){
for(int i = 0;i<n-1;++i){
bool isSwap = false;
for(int j = 0;j<n-1-i;++j){
if(arr[j]>arr[j+1]){
isSwap = true;
swap(arr[j],arr[j+1]);
}
}
if(!isSwap)
break;
}
}
int partition(int arr[],int l,int r){
int i = l-1;
int pivot = arr[r];
for(int j = l;j<r;++j){
if(arr[j]<pivot){
++i;
swap(arr[j],arr[i]);
}
}
swap(arr[r],arr[++i]);
return i;
}
void quickSort(int arr[],int l,int r){
if(l<r){
int pivot_index = partition(arr,l,r);
quickSort(arr,l,pivot_index-1);
quickSort(arr,pivot_index+1,r);
}
}
int main(){
int a[] = {2,4,6,7,8,9,2,3,4,1,9,2,1,6,2,3,22};
int size = sizeof(a)/sizeof(a[0]);
printArray(a,size);
quickSort(a,0,size-1);
printArray(a,size);
return(0);
}
I was practicing comparison based sorting algorithms in the above code. bubbleSort works fine but quickSort algorithm gives wrong result.
I usually compile my code using g++ compiler but sometime I also use clang++ For better code warning and suggestion.
When I compiled above code with clang++ it gave this warning
1.cpp:14:9: warning: unsequenced modification and access to 'a' [-Wunsequenced]
a^=b^=a^=b;
~~ ^
1 warning generated.
So there is a problem with the swap algorithm but my swap algorithm logic is correct. I used the same swap in bubbleSort and this worked with this. algorithms(bubbleSort).
But it's not working with quickSort logic.
I just want to know why it's not working with quick sort.