c - 实现快速排序时出现段错误

标签 c segmentation-fault

我想实现堆排序。为此,我经历了这个 http://faculty.simpson.edu/lydia.sinapova/www/cmsc250/LN250_Tremblay/L06-QuickSort.htm#basic教程并编写了以下代码:

#include <stdio.h>


int quick_sort(int a[],int first,int last);

int main()
{
    int a[]= {12,3,4,23,1,7,9,34,89,45};
    int i;
    printf("Enter 10 integers: \n");

    for ( i = 0 ; i < 10 ; i++ )
    {
        scanf("%d",&a[i]);
        printf("\t%d\n",a[i]);
    }
    for ( i = 0 ; i < 10 ; i++ )
    {
        printf("\n%d ",a[i]);
    }
    quick_sort(a,0,9);

    for ( i = 0 ; i < 10 ; i++ )
    {
        printf("%d ",a[i]);
    }
    return 0;
}

int quick_sort(int a[],int first,int last)
{
    int i,j,pivot,temp ;

    if ( first - last <= 1 && first - last >= -1 )
    {
        return 0;
    }
    else
    {
        i = first ;
        j = last ;

        pivot = a[(i+j) / 2 ] ;

        while ( i != j )
        {
            while ( a[i] < pivot )
            {
                i++;
            }
            while( a[j] > pivot )
            {
                j--;
            }

            temp = a[i] ;
            a[i] = a[j] ;
            a[j] = temp ;
        }
    }
    quick_sort(a,0,i-1);
    quick_sort(a,j+1,9);
    return 0;

}

使用 gcc 编译器运行它时出现段错误。请帮我解决一下。

最佳答案

问题的 quick_sort() 函数中有几件事对我来说是个谜。并不是说他们错了;只是我忘记了各种操作的目的。

经过一段时间的努力,这是我的版本:

void quick_sort(int *a, int first, int last)
   {
   int i,j,pivot,temp;

   if(last <= 1)
       return;

   pivot = a[first + last/2];

   j = first + last/2;
   temp = a[first];
   a[first] = a[j];
   a[j] = temp;

   j = first;
   for(i = first+1; i < first+last; i++)
      {   
      if(a[i] < pivot)
         {
         j++;
         temp = a[i];
         a[i] = a[j];
         a[j] = temp;
         }
      }

   temp = a[first];    
   a[first] = a[j];
   a[j] = temp;

   quick_sort(a, first, j-first);
   quick_sort(a, j+1, first+last-j-1);
   return;
   }

工作剧透测试用例 here .

关于c - 实现快速排序时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23815092/

相关文章:

c - 关于 CPU 利用率

c - 如果我有一个整数值大于 1024 的文件描述符,select() 仍然可以处理它吗?

C 类型在传递给函数时从 char* 转换为 int

c - 使用自制的 strstr() 函数检查其他字符串中嵌入的字符串,然后将其替换为其他字符串(由用户输入)

c++ - Lambda machine-dependent segmentation-fault(可能是编译器错误?)

c - 为什么我的 3d 数组是相反的?

c - 在 C 中寻找函数的局部最大值的问题

c - 段错误 - C 编程

c - 贪心看电视算法

c - 增加 C 中的指针导致段错误,即使它在数组大小内