I am doing this homework assignment in my data structures & algorithms class that asks me to make an array of random numbers, an array of counters, and make our own sorting algorithm using both arrays in C++.
The array of counters would basically contain the index of where each element is supposed to go when the array of numbers is sorted, such that the value of counters[i] would be the index where array[i] would go after it's sorted. It uses this code, and it was given by our professor:
for (int i = 1; i < arraySize; i++)
for (int j = 0; j < i; j++)
{
if (array[i] < array[j])
counters[j]++;
else
counters[i]++;
}
I thought that using both of the arrays, we would be able to design a sorting algorithm that would have a O(n) time complexity, so I tried to think of a way to do this, and I came up with this:
for (int i = 0; i < arraySize; i++)
{
int index = counters[i];
swap(array[i], array[counters[i]]);
swap(counters[i], counters[index]);
}
For every iteration, I am swapping array[i] with array[counters[i]] because counters[i] determines the index for array[i], and then I am also swapping the values in the counters to make sure that the counters stay in the same index as their corresponding value.
For some reason, this is not achieving the sorting correctly, but I don't understand why.
I'm thinking to use another sorting algorithm, but I wanted to try this one first because it would be O(n).
Anyone could help?
Thanks.
O(n). Are you supposed to be implementing a counting sort? With a restricted range of inputs, that can get down toO(n + k)(on both time and space) wherenis the input size, andkis the range of values, so a relatively restrictive range would be effectivelyO(n).