选择排序算法数组排序异常:负数数组无法正确排序
问题分析与修复
你的选择排序代码在处理含负数的数组时排序失败,核心问题出在getMaxIndex函数的遍历逻辑上:
- 循环终止条件错误:原代码中
for (int i = 0; i < last; i++)会漏掉索引为last的元素,导致无法在完整的[0, last]区间内找到最大值。 - 循环起始值逻辑冗余:函数接收了
start参数却未使用,始终从i=0开始遍历,虽当前调用场景下start固定为0,但逻辑上存在缺陷。
修正后的代码
只需修改getMaxIndex函数,确保遍历区间内的所有元素:
static void selection(int[] array) { for (int i = 0; i < array.length; i++) { int last = array.length - i - 1; int max= getMaxIndex(array, 0, last); swap(array, max, last); } } static void swap(int[] arr, int first, int second) { int temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } static int getMaxIndex(int[] arr, int start, int last) { int max = start; // 从start遍历到last(包含last),覆盖完整区间 for (int i = start; i <= last; i++) { if (arr[max] < arr[i]) { max = i; } } return max; }
修复说明
修正后的getMaxIndex函数会从start开始,遍历到last(包含该索引),确保在指定区间内找到真正的最大值索引。无论数组元素是正数还是负数,都能完成正确的选择排序。
内容的提问来源于stack exchange,提问作者Priyanshu Naudiyal
相关产品推荐
相关产品推荐

