I'm making a program of quick sort which prints the sorted elements of the arry but when I run the code I get segmentation fault
#include <iostream>
using namespace std;
int partition(int arr[],int left,int right,int pivot) {
while(left <= right) {
while(arr[left] < pivot) {
left ;
}
while(arr[right] > pivot) {
right--;
}
if(left <= right) {
swap(arr[left],arr[right]);
left ;
right--;
}
}
return left;
}
void quick_sort(int arr[],int left,int right) {
int pivot = arr[(left right)/2];
int index = partition(arr,left,right,pivot);
quick_sort(arr,left,index-1);
quick_sort(arr,index,right);
}
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,10};
int size = sizeof(arr)/sizeof(arr[0]);
quick_sort(arr,0,size-1);
for(int i = 0; i < size; i ) {
cout << arr[i] << " ";
}
return 0;
}
I was expecting a soted arrray of elements which are hardcoded.
CodePudding user response:
Add this to top your quick_sort function
if (left >= right)
return;