1

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.

4

2 回答 2

1
for(i=0;i<right+1;i++)
{
    if(arr[i]>=0)
    break;
}

这部分看起来很可疑。权利可以成为最后一个元素吗?

于 2013-11-09T08:27:12.030 回答
0

要回答您的第一个问题:打印是缓冲的。因此,如果您的程序崩溃,缓冲区还没有被刷新,并且“调试”也不会被打印出来。尝试打印到 stderr 以用于记录和错误目的:

fprintf(stderr, "Debug");

我也会尝试回答您有关段错误的问题。

更新:

如果 arr 中的所有值都大于零,这将导致负枢轴:

while(j>=left && arr[j]>=temp)
    j--;

如果你改变:

int temp = 0;

to: int temp = arr[left];

它不会给你一个分段错误,我认为这是你想要的。请注意,这不会修复您的排序算法,只会指定您的段错误发生的位置。

于 2013-11-09T08:25:00.457 回答