简体   繁体   English

C 快速排序分段错误

[英]C quicksort segmentation fault

I want to write a quicksort code in c, the compiler complains " Segmentation fault (core dumped)" when I try to run this code.我想用 c 编写快速排序代码,当我尝试运行此代码时,编译器会抱怨“分段错误(核心转储)”。 I can't find where the problem is.我找不到问题出在哪里。 Could someone help me find the problem ?有人可以帮我找到问题吗? Thanks.谢谢。

#include <stdio.h>

void swap(int *m,int *n)
{
  int t;
  t = *m;
  *m = *n;
  *n = t;
}

int partition(int *a,int lo,int hi)
{
  int pivot = a[hi];
  int i = lo;
  for(int j = lo;j < hi;j++)
    {
      if(a[j] < pivot)
    {
      //swap(&a[i],&a[j]);
      int t = a[i];
      a[i] = a[j];
      a[j] = t;
      i++;
    }
    }
  // swap(&a[i],&a[hi]);
  int t = a[hi];
  a[hi] = a[i];
  a[i] = t;
  return i;
}

void quicksort(int *a,int lo,int hi)
{
  if(lo < hi)
    {
      int p = partition(a,lo,hi);
      quicksort(a,lo,p);
      quicksort(a,p+1,hi);
    }
}

int main(void)
{
  int a[10] = {3,4,6,7,5,8,9,2,1,0};
  quicksort(a,0,9);
  for(int i = 0;i < 10;i++)
    printf("%d ",a[i]);
  return 0;
}

Well it appears you have made a simple mistake understanding quick sort.好吧,您似乎在理解快速排序时犯了一个简单的错误。

The thing is you put pivot element in the correct position inside array while calling partition() .问题是您在调用partition()时将枢轴元素放在数组内的正确位置。

What I mean to say is consider the elements initially inside array as我的意思是将数组中最初的元素视为

[ 3 , 4 , 6 , 7 , 5 , 8 , 9 , 2 , 1 , 4 ] [ 3 , 4 , 6 , 7 , 5 , 8 , 9 , 2 , 1 , 4 ]

Now after calling partition() , the array should look like this (kindly note that you have selected last element as pivot element , marked with bold above)现在调用partition() ,数组应该如下所示(请注意,您选择了最后一个元素作为枢轴元素,上面用粗体标记)

[ 3 , 2 , 1 , 4 , 5 , 8 , 9 , 4 , 6 , 7 ] [ 3 , 2 , 1 , 4 , 5 , 8 , 9 , 4 , 6 , 7 ]

Now the array should be divided into three parts现在数组应该分为三部分

[ 3 , 2 , 1 ] [ 4 ] [ 5 , 8 , 9 , 4 , 6 , 7 ] [ 3 , 2 , 1 ] [ 4 ] [ 5 , 8 , 9 , 4 , 6 , 7 ]

We know that the pivot element is in correct position , so no need to touch the middle part, just proceed with remaining left and right part.我们知道枢轴元素在正确的位置,所以不需要接触中间部分,只需继续剩下的左右部分。

What you have done is considered only two part after partition()您所做的仅被认为是partition()之后的两部分

[ 3 , 2 , 1 , 4 ] [ 5 , 8 , 9 , 4 , 6 , 7 ] [ 3 , 2 , 1 , 4 ] [ 5 , 8 , 9 , 4 , 6 , 7 ]

Now for [ 3 , 2 , 1 , 4 ] , when you call quicksort() , it will fall in infinite recursion.现在对于 [ 3 , 2 , 1 , 4 ] ,当您调用quicksort() ,它将陷入无限递归。

I have modified the portion below , hope it helps我修改了下面的部分,希望它有帮助

void quicksort(int *a,int lo,int hi)
{
  if(lo < hi)
    {
      int p = partition(a,lo,hi);
      quicksort(a,lo,p-1);
      quicksort(a,p+1,hi);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM