快速排序函数触发"exited, segmentation fault"错误求助
帮你修复快速排序的段错误问题
嘿,我来帮你搞定这个快速排序的段错误!你遇到的问题主要是几个逻辑上的小疏漏,咱们一步步梳理清楚:
核心问题分析
1. 递归没有被正确包裹,导致无效调用
你的代码里,交换pivot和递归调用的语句在if(first < last)的外面——这意味着哪怕区间已经无效(比如first >= last),这些代码依然会执行。举个例子,当递归到loop_variable为0时,会调用quicksort_fixed(number, 0, -1),这时候函数里访问number[pivot](pivot是-1)直接就越界了,触发段错误。
2. 分区逻辑不完整,只执行了一轮指针移动
快速排序的分区需要不断移动左右指针、交换元素,直到两个指针相遇才行。但你现在的代码只做了一轮指针查找和交换就结束了,根本没完成分区,后续递归自然会出问题。
修正后的完整代码
#include <stdio.h> void swap(int a[], int b, int c){ int temp = a[b]; a[b] = a[c]; a[c] = temp; } void quicksort_fixed(int *number, int first, int last){ if(first < last){ // 仅处理有效区间 int pivot = last; int smaller_index = first; int loop_variable = last; // 外层循环:重复移动指针直到相遇,完成分区 while(smaller_index < loop_variable){ // 从左找第一个大于pivot的元素 while(number[smaller_index] <= number[pivot] && smaller_index < loop_variable){ smaller_index++; } // 从右找第一个小于等于pivot的元素 while(number[loop_variable] > number[pivot] && smaller_index < loop_variable){ loop_variable--; } // 交换两个指针指向的元素 if(smaller_index < loop_variable){ swap(number, smaller_index, loop_variable); } } // 将pivot交换到分区后的正确位置 swap(number, pivot, loop_variable); // 递归排序左右子数组 quicksort_fixed(number, first, loop_variable - 1); quicksort_fixed(number, loop_variable + 1, last); } // 区间无效时直接返回,终止递归 } void test_quicksort_fixed(){ printf("\nUnsorted List 1: "); int a[6] = {5,2,3,1,4,6}; for (int i=0; i < 6; i++){ printf("%d, ", a[i]); } printf("\nSorted List 1: "); quicksort_fixed(a,0,5); for (int i=0; i < 6; i++){ printf("%d, ", a[i]); } } int main(){ test_quicksort_fixed(); return 0; }
关键修正点说明
- 包裹递归逻辑:把所有分区、交换、递归的代码都放进
if(first < last)块里,确保只有当区间有效时才处理,彻底避免无效递归和数组越界。 - 完整分区循环:添加外层
while(smaller_index < loop_variable)循环,让指针反复移动、交换,直到相遇,完成完整的分区操作。 - 正确的pivot交换时机:只有在分区完成后,才把pivot元素交换到指针相遇的位置,保证分区结果正确。
现在运行这段代码,应该能正常排序,不会再触发段错误啦!
内容的提问来源于stack exchange,提问作者Immort8lSp8rt8n
相关产品推荐
相关产品推荐

