Sort an array in C from low to high (without using qsort)

I have functions that take an array of numbers and sort them from low to high. So far I have this algorithm, however the output is not what I expect. Can someone shed light on him. I can not use any functions of the C library.

/* 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); } 
+4
source share
5 answers

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

The valid index in array 0 is count-1 .
Since you are accessing the value at index i+1 in a loop:

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

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

+5
source

You are trying to implement a bubble sorting algorithm. Read this to understand that your code is missing .

+5
source

The value k , but the variable is never initialized or assigned. At some point, your code will try to access the numbers[count] value when the array containing the count elements has a maximum index of count-1

0
source

You did not initialize k .

The algorithm will stop as soon as it moves only one number. You need to move all of them.

I think you are missing the for loop on k outside the while loop, but since I'm not quite sure what you are trying to do here, I cannot be sure.

Why can't you implement your own qsort () function? It is allowed? Try reading a few sorting algorithms online.

0
source

if (numbers [i]> numbers [k]) {

it should be

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

k not used at all.

 for (i = 0;i <= count;i++){ 

it should be

 for (i = 0; i < count-1;i++){ 

since there are only elements from 0 to count-1, and then you compare them with the next. The name for j is shit. Make it the logical name didSwap. And then rethink your codification, maybe it's just the other way around ...

0
source

All Articles