C++实现SelectionSort排序失败,请求问题排查帮助
选择排序代码错误排查与修正
初始代码的核心错误
- 索引变量赋值错误:
firstIndex = arr[i];将数组元素值赋值给了索引变量,正确逻辑是把当前起始索引赋值给它:firstIndex = i;。原代码后续用arr[firstIndex]会访问错误内存地址,导致出现垃圾值-858993460。 - 循环边界错误:
- 外层循环
i < n - 2范围过小,应改为i < n - 1,确保最后一个未排序元素被处理。 - 内层循环
j < n - 1未遍历到数组最后一个元素,需改为j < n。
- 外层循环
- 交换时机错误:
swap(arr[i], arr[firstIndex]);放在内层循环内部,每次比较后都交换,违背了选择排序“先找到最小元素索引,再一次性交换”的核心逻辑。
更新后代码的遗留错误
- 变量名大小写错误:
- 函数内声明了
int I;,但循环使用未定义的i,需统一为int i;。 - main函数中循环变量是
int i,输出时却用array[I],大小写不匹配导致输出异常。
- 函数内声明了
- 交换时机仍错误:
swap操作依然放在内层循环中,算法逻辑变成类似冒泡排序,而非选择排序。
修正后的完整代码
#pragma once #include <iostream> using namespace std; void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void SelectionSort(int *arr, int n) { cout << "Selection SORT start\n"; for (int i = 0; i < n - 1; i++) { int minIndex = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } // 找到最小元素索引后,仅执行一次交换 swap(arr[i], arr[minIndex]); } cout << "Selection SORT end\n"; }
#include <iostream> #include "SelectionSort.h" using namespace std; int main() { int array[] = {5, 8, 1, 6}; int size = sizeof(array) / sizeof(array[0]); cout << "unaltered array\n"; for (int i = 0; i < size; i++) { cout << array[i] << " "; } cout << endl; SelectionSort(array, size); cout << "sorted array\n"; for (int i = 0; i < size; i++) { cout << array[i] << " "; } cout << endl; }
修正后输出
unaltered array 5 8 1 6 Selection SORT start Selection SORT end sorted array 1 5 6 8
内容的提问来源于stack exchange,提问作者SurlyGent
相关产品推荐
相关产品推荐

