Strange bubble sorting behavior

Can someone explain why this bubble sorting function doesn't work and why am I losing numbers in my output? I am very new to C, so please forgive me if this is something very obvious I missed.

#include <stdio.h> #include <stdlib.h> int bubble(int array[],int length) { int i, j; int temp; for(i = 0; i < (length); ++i) { for(j = 0; j < (length - 1); ++j) { if(array[i] > array[i+1]) { temp = array[i+1]; array[i+1] = array[i]; array[i] = temp; } } } return 0; } int main() { int array[] = {12,234,3452,5643,0}; int i; int length; length = (sizeof(array)/sizeof(int)); printf("Size of array = %d\n", length); bubble(array, length); for (i = 0; i < (length); ++i) { printf("%d\n", array[i]); } return 0; } 

Exit

 Size of array = 5 12 234 3452 0 0 
+4
source share
4 answers
 for (i = 0; i < (length-1); ++i) { for (j = 0; j < (length-i-1); ++j) { if(array[j] > array[j+1]) { temp = array[j+1]; array[j+1] = array[j]; array[j] = temp; } } } 

In bubble sorting, you only use the internal loop variable.

+3
source

In your inner loop you are not using j at all. Double check your logic. Also note that the array [i + 1] is out of bounds of the array.

+4
source

Another thing, the inner loop goes from 0 to i , if I remember well; but I think that only optimization (since the tail remains sorted at every step).

Try to follow your code step by step with paper and a pencil. It always works.

0
source
 for (i = 0; i < (length); i++) { for (j = 1; j < (length-i); j++) { if(array[j-1] > array[j]) { temp = array[j-1]; array[j-1] = array[j]; array[j] = temp; } } } 
0
source

Source: https://habr.com/ru/post/1309275/


All Articles