0

I tried to bubble sort but when i output it, it gives me funky numbers. Can you help me out.
is the bubble sort even right?

#include <stdio.h>

int sort(int a[], int len)
{
	int x, y, t;
	
	for (x=0; x < len-1; x++)
	{
		for (y=0; y < len-x-1; y++)
        {
			if (a[y] > a[y+1])
			{
				t=a[y];
				a[y]=a[y+1];
				a[y+1]=t;
			}
		}
	}
	return t;
}
int main (void)
{
	int i,x,a[10], len;
	
	printf("len of array: ");
	scanf("%d", &len);
	for (x = 0; x < len; x++)
	{
		printf("Enter numbers: ");
		scanf("%d",&a); 
	}
	printf("Sorted array: \n");

	for (i = 0; i < len; i++)
	{	sort(a, len);
		printf("%d ", a[i]);
	}

}
2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by jonsca
0

scanf("%d",&a); is reading the numbers into the same spot in the array "a" over and over again. Hence all the other spots are stuck with their uninitialized "values." You can fix it by using the index x as scanf("%d",&a[x]); but see http://www.daniweb.com/tutorials/tutorial45806.html for some safer alternatives to scanf.

There's one way to measure if your sort works. Test it out (it does seem to work -- but your looping over your function multiple times in main is extraneous).

Edited by jonsca: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.