Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an Array in C from low to high (without using qsort)

I have a functions, which takes an Array of numbers, and sort them from low to high. So far, I have this algorithm, however the output isn't what I'm expecting. Can someone shed some light on it. I cannot use any C library functions.

/* 
   Sort "count" numbers stored in array numbers[] in non-decreasing order.
   There may be duplicate numbers in the array.
   You may use any sorting algorithm that you know.
 */

void sort( double numbers[], int count )
{
    int i, j, k;
    //printf("%d", count);

    double temp;
    do{
        j = 0;  
        for (i = 0;i<=count;i++){
                if (numbers[i] > numbers[i+1]){//this was numbers[k], which was an error
                    j = 1;
                    temp = numbers[i];
                    numbers[i] = numbers[i+1];
                    numbers[i+1] = temp;
                }
            }
    } while (j == 1);
}
like image 287
smooth_smoothie Avatar asked Dec 28 '22 04:12

smooth_smoothie


2 Answers

The condition in for loop i<=count is incorrect.

Valid index in the array are 0 to count-1.
Since you are accessing value at index i+1 in the loop:

if (numbers[i] > numbers[i+1])

i can take the value from 0 to count-2, so change the condition to i<=count-2 or i<count-1

like image 187
codaddict Avatar answered Mar 08 '23 02:03

codaddict


You are trying to implement the bubble sort algorithm. Read this to understand what your code is missing.

like image 45
bcosca Avatar answered Mar 08 '23 03:03

bcosca