EDIT: I've solved the issue! It had nothing to do with the function itself. I initially used a vector for this function, and the cout statement I used to check the function in main() still called the vector, not the array. A simple mistake, but I appreciate the help!
Hey! I'm currently in college learning data structures, and for our final project, we're tasked with creating multiple sorting algorithms to sort 500,000 randomly generated numbers between 1 - 9,999,999 that have been defined in a text file. I'm currently trying to work on a counting sort, and I keep getting the #include vector line 1553 error 'vector subscript out of range'. I've debugged this function all the way to the last for-loop. Everything seems to work perfectly fine, so I'm assuming it has to do with somewhere in this final piece, but I'd prefer to not have to manually go through 500,000 cycles, so if anyone can see what I've done wrong, I'd like to know.
I also allocated this data on the heap because stack allocation creates a memory overload.
I apologize if this is a low-level question, but I'd love some help, as this project means a lot to me and to my grade. Thank you!
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;
}