I'm learning C and my bubble sort code returns a random number sometimes (although sometimes it does returns the correct array numbers).
For example, it should print {0, 1, 3, 10}. But sometimes prints things like {-487420160, 0, 1, 3} or {-1484260208, 0, 1, 3} (only the first number changes, the other are correct).
This is the code:
#include <stdio.h>
int main(){
//array and variables
int arr[] = {1, 3, 0, 10};
int len = sizeof(arr)/ sizeof(int);
int j = 0;
int i = 0;
//print original array
printf("ORIGINAL ARRAY: \n");
printf("{");
for (int x = 0; x < len; x ){
printf("%d", arr[x]);
if (x < len-1){
printf(", ");
}
}
printf("}\n");
//sorting
for ( i = 0;i < len; i ){
for (j = 0 ;j < len; j ){
if(arr[j] > arr[j 1]){
int temporal = arr[j];
arr[j] = arr[j 1];
arr[j 1] = temporal;
}
}
}
//print sorted array
printf("BUBBLE-SORTED ARRAY: \n");
printf("{");
for (int y = 0; y < len; y ){
printf("%d", arr[y]);
if (y < len-1){
printf(", ");
}
}
printf("}\n");
return 0;
}
Do anybody know why or can help me improve the code?
CodePudding user response:
In place of the for(j=0:j<len;j ) change to for(j=0:j<len-1;j )
for ( i = 0;i < len; i ){
for (j = 0 ;j < len; j ){// here instead of len use len-1
if(arr[j] > arr[j 1]){
int temporal = arr[j];
arr[j] = arr[j 1];
arr[j 1] = temporal;
}
}
}
Now, in bubble sort we usually compare untill the end, but in your case when j=len then j 1 is a random number which has no existence and there is no element.
Make the following change and you will get the solution.
Also in C I would like you to declare all variables at one place, as C doesn't like to have a variable declared in between program execution.
#include <stdio.h>
int main(){
//array and variables
int arr[] = {1, 3, 0, 10};
int len = sizeof(arr)/ sizeof(int);
int j = 0;
int i = 0;
int x=0;
int y=0;
//print original array
printf("ORIGINAL ARRAY: \n");
printf("{");
for (x = 0; x < len; x ){
printf("%d", arr[x]);
if (x < len-1){
printf(", ");
}
}
printf("}\n");
//sorting
for ( i = 0;i < len; i ){
for (j = 0 ;j < len-1; j ){// Here is the change, len has been changed to len-1
if(arr[j] > arr[j 1]){
int temporal = arr[j];
arr[j] = arr[j 1];
arr[j 1] = temporal;
}
}
}
//print sorted array
printf("BUBBLE-SORTED ARRAY: \n");
printf("{");
for (y = 0; y < len; y ){
printf("%d", arr[y]);
if (y < len-1){
printf(", ");
}
}
printf("}\n");
return 0;
}