Home > Mobile >  Getting an unknown value while trying to sort an array in c programming
Getting an unknown value while trying to sort an array in c programming

Time:03-15

I am using VS code. I was sorting an array in c using bubble sort method. It seems to sort right, But I am getting number 4 at the end which is not in the array. here is the code and output.

#include <stdio.h>

int bubble_sort(int nums[], int size);

int main() {
    int nums[] = { 101, 201, 111, 23, 41, 33, 1 };
    
    int size = sizeof(nums) / sizeof(int);
    
    int buble = bubble_sort(nums, size);
    
    printf("%d\n", buble);
}

//  defining bubble sort  
int bubble_sort(int nums[], int size) {

    for (int a = 0; a < size - 1; a  ) {
        for (int b = 0; b < size - a - 1; b  ) {
            //swapping
            if (nums[b] > nums[b   1]) {
                nums[b] = nums[b] ^ nums[b   1];
                nums[b   1] = nums[b] ^ nums[b   1];
                nums[b] = nums[b] ^ nums[b   1];
            }
        }
    }
    for (int i = 0; i < 7; i  ) {
        printf("%d\n", nums[i]);
    }
}

output I am getting:

1
23
33
41
101
111
201
4

This is the output I am getting. Here, see the last number. It is not there in the array. I have no idea where this number is from. I tried debugging but it is coming from somewhere. Could anyone tell me from where and Why I am getting this number.

CodePudding user response:

This line doesn't make sense.

printf("%d\n",buble);

You're printing the return value of the bubble_sort function, but it doesn't have a return statement, so you don't know what that is going to return.

You should be compiling with the -Wall option. If you do, you'll get warnings about things you're doing wrong, including this one:

bubble.c: In function ‘bubble_sort’:
bubble.c:33:3: warning: control reaches end of non-void function [-Wreturn-type]

It's saying "You have a function that wants to return a value, and you have no return statement."

CodePudding user response:

You're using loop inside buble_sort function to print the output on the screen. You don't have to set return type to int or store its return value in a new variable which will take extra space in memory.

Since your function does not have a return value and you've prototyped return type as int, it is possibly printing the size of int (which is 4 byte).

I suggest you to change below lines :

int bubble_sort(int nums[], int size);

int buble = bubble_sort(nums,size);   

int bubble_sort(int nums[],int size){

to this

void bubble_sort(int nums[], int size);    

bubble_sort(nums,size);

int bubble_sort(int nums[],int size){

and delete below

printf("%d\n",buble);
  • Related