0

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;
}
1

One problem I see with your sort function is that you've made a third array (sortedArray[]) and filled it with sorted numbers from values[], but then you didn't do anything else with it. Your function doesn't return it (not that you can return an array in C anyway, afaik).

This sort function is not supposed to return anything, hence return type void. Instead of writing your sorted numbers into another array, consider writing them directly into values[] array.

| improve this answer | |
  • Thank you!!!!!!! – Milad Apr 2 '17 at 1:07
  • Happy to help :) – ArtemPetrov Apr 2 '17 at 1:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .