计数排序算法出现‘vector subscript out of range’报错排查(已解决)
计数排序下标越界问题排查与解决
编辑说明: 已解决问题!该问题与计数排序函数本身无关。最初我使用vector实现该函数,但main函数中用于验证的cout语句仍调用了vector而非数组,这是一个简单失误,感谢帮助!
问题描述
我是一名正在学习数据结构的大学生,期末项目要求实现多种排序算法,对文本文件中500000个取值范围为1-9999999的随机生成数进行排序。当前我在实现计数排序时,频繁出现#include <vector>第1553行的“vector subscript out of range”错误。我已调试至最后一个for循环,此前所有步骤均运行正常,因此推测问题出在最后一段代码中,但不愿手动遍历50万次循环,希望有人能指出问题所在。
此外,我采用堆内存分配存储数据,避免栈分配导致内存过载。若这是基础问题我深表歉意,但该项目对我的成绩至关重要,恳请帮助!
实现代码
void countingSort(int numberArray[], int SIZE) { // Initializer for dynamically-allocated array used to hold the sorted data in the array int* sortedArray = new int[SIZE]; // Initializes all values in sortedArray to 0 for (int i = 0; i < SIZE; i++) sortedArray[i] = 0; // Initializer for variable used to hold the maximum value in the original data int max = 0; // Finds the max in numberArray for (int i = 0; i < SIZE; i++) { if (numberArray[i] > max) max = numberArray[i]; } // Create an array to store the amount of times each number in numberArray is used int* countArray = new int[max + 1]; // Initialize all indexes of countArray to 0 for (int i = 0; i <= max; i++) { countArray[i] = 0; } // When a number is present in numberArray, increase its number of appearances in countArray by one for (int i = 1; i < SIZE; i++) countArray[numberArray[i]]++; // Find the total frequency in the count array for (int i = 1; i <= max; i++) countArray[i] += countArray[i - 1]; // Store the sorted values into a sorted array // Decrease the total count number for (int i = SIZE - 1; i > 0; i--) { sortedArray[countArray[numberArray[i]] - 1] = numberArray[i]; countArray[numberArray[i]]--; } // Store the sorted array in the original numberArray for (int i = 0; i < SIZE; i++) { numberArray[i] = sortedArray[i]; } } int main() { int* SIZE = new int; *SIZE = 500000; . (*code for other functions*) . countingSort(numberArray, *SIZE); cout << "\n" << numberList[0] << "\t" << numberList[499999] << endl; }
内容的提问来源于stack exchange,提问作者beargrammer
相关产品推荐
相关产品推荐

