This program uses quicksort to sort the numbers followed by the code which places the negative and positive numbers alternatively.
#include<stdio.h>
#include<stdlib.h>
void swap(int *arr,int i,int j)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
int partition(int *arr,int left,int right)
{
int temp=0;
int i=left;
int j=right;
while(i<=j)
{
while(i<=right && arr[i]<=temp)
i++;
while(j>=left && arr[j]>=temp)
j--;
if(i<j)
swap(arr,i,j);
}
return j;
}
void quick_sort(int *arr,int left,int right)
{
if(left<right)
{
int pivot=partition(arr,left,right);
quick_sort(arr,left,pivot-1);
quick_sort(arr,pivot+1,right);
}
return ;
}
void nega(int *arr,int left,int right)
{
int i;
quick_sort(arr,left,right);
for(i=0;i<right+1;i++)
{
if(arr[i]>=0)
break;
}
int j=i;
int k;
for(i=1,k=j;i<j && k<=right;i+=2,k++)
{
int temp=arr[i];
arr[i]=arr[k];
arr[k]=temp;
}
}
int main()
{
int i,n;
int arr[15];
printf("enter the n:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the element");
scanf("%d",&arr[i]);
}
printf("debug");
nega(arr,0,n-1);
for(i=0;i<n;i++)
printf("%d",arr[i]);
return 0;
}
Here the code asks the user to value of n and it takes n elements into the array. If the value of the n is 1(i.e., for one element)it is working fine. If the value of the n > 1 (for more than 1 element).It is showing segmentation fault.May be somewhere in the functions it access unaccessible locations.
But,I don't understand why it is not executing printf("debug");
right after the input to the code.It is directly showing segmentation fault before executing printf("debug");
and I don't find any cause for segmentation fault before printf("debug");
.
Can someone point out me what is the problem.Thanks.