### quicksort

i am getting a segmentation fault at line 12. when i tried to print temp, it went in infinite loop. can you tell me the reason behind this and how to correct it(si-starting index, ei - end index)

using namespace std;
#include<iostream>
void partition(int arr[],int si,int ei)
{
int i,count=0, temp;
for(i=si+1;i<=ei;i++)
{
if(arr[si]>arr[i])
count++;
}
int index = count ;
temp= arr[si]; // here is the error
cout<<temp<< " ";
arr[si]=arr[index];
arr[index]=temp;

}
void quicksort(int arr[],int si,int ei)
{
if(si>=ei)
{
return;
}
int temp;
int x= arr[si];
partition(arr,si,ei);
int i=si, j= ei;
while( i!=j)
{
if(arr[i]<x)
{
i++;
}
else if(arr[j]>x)
{
j--;
}
else if((arr[i]>x) && (arr[j]<x))
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;

}

}
quicksort(arr,si,x-1);
quicksort(arr,x+1,ei);
}
int main()
{
int arr[100],n,i;
cin>>n;
for(i=0;i<n;i++)
{
cin>>arr[i];
}
quicksort(arr,0,n-1);
for(i=0;i<n;i++)
{
cout<<arr[i];
}
return 0;
}
Last edited on
what is the value of si when it crashes?

or a better question:
quicksort(arr,si,x-1);
quicksort(arr,x+1,ei);

what is x??
int x= arr[si];

so if you have an array:
[-10000000, 32, 11,5000000000];
x = arr[s1].
x = -10000000....
quicksort(arr, 0, -10000000-1); ... ?!
 can you tell me the reason behind this

Use the debugger to trace through the code monitoring variable values so that you see what is happening during the code execution. When you find where the code is not executing as expected, then you have found a problem. Being able to use the debugger to find run-time problems in code is a skill that all programmers need to acquire. The sooner the better.