-
simple bubble sort
ive tried to implement a simple bubble sort on 8 items in an array however whenever i execute it i get random values out of memory, here is my code
Code:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main(void)
{
int a[]={1,2,3,4,5,6,7,8};
printf("%s",a);
bubble(a,8);
printf("%s",a);
}
int bubble(int a[],int n)
{
int i,j;
for(i=0; i<n-1;++i)
for(j=n-1;i<j;--j)
if(a[j-1]>a[j])
swap(&a[j-1],&a[j]);
}
int swap(int *p, int *q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}
where have i gone wrong?
-
Your functions aren't prototyped, both bubble and swap return nothing, so void would be a better return value, and a is not a string, so the %s format modifier is a poor choice. You really need to use a loop and %d. It's also hard to tell how well the sort works when the input is already sorted. ;)
Code:
#include<stdio.h>
void bubble(int a[],int n);
void swap(int *p, int *q);
int main(void)
{
int a[]={7,6,5,4,3,2,1};
int i;
for (i = 0; i < 7; i++)
printf("%d ",a[i]);
printf("\n");
bubble(a,8);
for (i = 0; i < 7; i++)
printf("%d ",a[i]);
printf("\n");
}
void bubble(int a[],int n)
{
int i,j;
for(i=0; i<n-1;++i)
for(j=n-1;i<j;--j)
if(a[j-1]>a[j])
swap(&a[j-1],&a[j]);
}
void swap(int *p, int *q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}
-
thanks , are the function prototypes necessarry?
-
>are the function prototypes necessarry?
No, but functions must be declared before you use them. This means either providing the declaration in the form of a prototype, or defining the function before its use. An equivalent solution without prototypes would be:
Code:
#include<stdio.h>
void swap(int *p, int *q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}
void bubble(int a[],int n)
{
int i,j;
for(i=0; i<n-1;++i)
for(j=n-1;i<j;--j)
if(a[j-1]>a[j])
swap(&a[j-1],&a[j]);
}
int main(void)
{
int a[]={7,6,5,4,3,2,1};
int i;
for (i = 0; i < 7; i++)
printf("%d ",a[i]);
printf("\n");
bubble(a,8);
for (i = 0; i < 7; i++)
printf("%d ",a[i]);
printf("\n");
}
A definition is also a declaration, so the requirement that swap be declared before its use in bubble and bubble be declared before its use in main is met. Of course, now the code is order dependent. If you move swap below bubble then it won't work.
-
thanks for the explanation