can someone please look at my code and tell me where I went wrong with my counting sort algorithm (Or binary search algorithm, if that's where the problem lies...?). Please and thank you.
Binary search algorithm:
bool search(int value, int values[], int n)
{
// Return false if n is not positive
if (n < 0)
{
return false;
}
// Implement binary search algorithm
int f = 0; // f for first
int l = n - 1; // l for last
int m = (f + l) / 2; // m for middle
while (f <= l)
{
// Return true if middle of array is desired value
if (value == values[m])
{
return true;
}
// If value is greater than middle, number proceeding m is now f
else if (value > values[m])
{
f = m + 1;
}
// If value is less than middle, number preceeding m is now l
else if (value < values[m])
{
l = m - 1;
}
// Reestablish middle after array cut in half
m = (f + l) / 2;
}
return false;
}
Counting sort algorithm:
void sort(int values[], int n)
{
int counterArray[65536] = {0};
int sortedArray[n];
// Loop through values
for (int i = 0; i < n; i++)
{
// For each value in the array
// Increment counter array in that position by 1
counterArray[values[i]]++;
}
int num = 0;
// Loop through counter array
for (int i = 0; i < 65536; i++)
{
// Check if value is greater than 0
if (counterArray[i] > 0)
{
// Loop through the count in that position of the counter array
for (int j = 0; j < counterArray[i]; j++)
{
// Add the number of the position to the sorted array for each count at that position
sortedArray[num] = i;
num++;
}
}
}
return;
}