I wrote the Quicksort code in c++ but it is not working. can anyone tell me what is wrong with this code? Whenever I am giving the input, it does not return any output. example:
5
5 4 3 6 2
Process exited after 5.997 seconds with return value 3221225725 Press any key to continue . . .
why is it not returning any output? even though I checked the code many time but still I am facing the same problem
#include<iostream>
using namespace std;
void swap(int *a, int *b) //swap function
{
int c;
c=*b;
*b=*a;
*a=c;
}
int partition(int arr[], int i, int j) //partition function
{
int pivot=arr[j];
while(i<j) {
while(i<=pivot) {
i++;
}
while(j>=pivot) {
j--;
}
if(i<j) {
swap(&arr[i],&arr[j]);
}
}
swap(&pivot,&arr[j]);
return j;
}
void quicksort(int arr[], int i, int j) //quicksort function
{
if(i<j) {
int p;
p=partition(arr,i,j);
quicksort(arr,i,p-1);
quicksort(arr,p+1,j);
}
}
void print(int arr[],int n) //function to print the array
{
for(int i=0;i<n;i++) {
cout<<arr[i]<<" ";
}
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++) {
cin>>arr[i];
}
int x=0,y=n-1;
quicksort(arr,x,y);
print(arr,n);
return 0;
}
It should be while(arr[i]<=pivot)
instead of while(i<=pivot)
same goes for j
int partition(int arr[], int i, int j)
{
int pivot=arr[j];
while(i<j) {
while(arr[i]<=pivot) {
i++;
}
while(arr[j]>pivot) {
j--;
}
if(i<j) {
swap(&arr[i],&arr[j]);
}
}
swap(&pivot,&arr[j]);
return j;
}