我正在编写一个快速排序功能,并且遇到了分段错误错误。我不确定为什么会这样。任何帮助表示赞赏。这是我的代码。我知道该错误意味着我正在尝试访问不存在的内存,但不确定该错误在哪里。

#include <stdio.h>

void swap(int arr[], int i, int j){
  int tmp;
  tmp = arr[i];
  arr[i] = arr[j];
  arr[j] = tmp;
}


int partition(int arr[], int first, int last){
  int pivot = arr[last];
  while(first <= last){
while(arr[first] < pivot){
  first++;
}
while(arr[last] > pivot){
  last--;
}
if(first <= last){
  swap(arr, arr[first], arr[last]);
  first++;
  last--;
}
}
}

void quickSortR(int arr[], int first, int last){
  if(last <= first) return;
  int mid = partition(arr, first, last);
  quickSortR(arr, first, mid-1);
  quickSortR(arr, mid+1, last);
}

void main() {
int arr[14] = {488888, 3, 5, 0, 23, 12124, 6, 7, 2, 1121, 0, 92, 5, 8};
quickSortR(arr, 0, 13);
for (int i = 0; i<14; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
}

最佳答案

分段故障在以下几行中:

  tmp = arr[i];
  arr[i] = arr[j];
  arr[j] = tmp;


您正在将数组元素发送到swap(分别作为i和j)并将其用作索引,显然,这些行将导致段错误,因为这些地址可能超出范围且被系统保留。

就像@Loc告诉的那样,“分区”函数应该返回中间值的索引,您也忘记了交换数据​​透视表。还有其他一些小的更正。我已包含正确的代码:

#include <stdio.h>

void swap(int arr[], int i, int j){
        int tmp;
        tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
}


int partition(int arr[], int first, int last){
        int pivot = arr[last];
        int p=last;
        last--;
        while(first <= last){
                while(arr[first] < pivot){
                        first++;
                }
                while(arr[last] > pivot){
                        last--;
                }
                if(first <= last){
                        swap(arr, first, last);
                        first++;
                        last--;
                }
        }
        swap(arr, first, p);
        return first;
}

void quickSortR(int arr[], int first, int last){
        if(last <= first) return;
        int mid = partition(arr, first, last);
        quickSortR(arr, first, mid-1);
        quickSortR(arr, mid+1, last);
}

void main() {
        int arr[14] = {488888, 3, 5, 0, 23, 12124, 6, 7, 2, 1121, 0, 92, 5, 8};
        int i;
        quickSortR(arr, 0, 13);
        for (i = 0; i<14; i++) {
                printf("arr[%d] = %d\n", i, arr[i]);
        }
}

09-20 10:26