简体   繁体   中英

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. 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() .

What I mean to say is consider the elements initially inside array as

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

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)

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

Now the array should be divided into three parts

[ 3 , 2 , 1 ] [ ] [ 5 , 8 , 9 , 4 , 6 , 7 ] ] [ 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()

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

Now for [ 3 , 2 , 1 , ] , when you call quicksort() , it will fall in infinite recursion. ] ,当您调用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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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