>Can anyone please help?
Be careful what you wish for. Let's start by shredding your code.
>#include <conio.h>
This is totally not needed. Get rid of it and use a standard solution instead. I'll come back to this shortly.
>void swap(int *, int *);
>void bubble(int [], int);
Others may not agree, but this is your interface, and it needs to be informative. That means naming your parameters. swap and bubble are both common names, so a prefix to avoid ambiguity is a good idea.
>main(){
The latest C standard prohibits the implicit int that you're using here. Even before C99 it was poor style, so you should consider using a conventional definition of main:
Code:
int main ( void )
{
return 0;
}
>printf("I will arrange these numbers in order");
What numbers? I'm a user and I'm incredibly stupid. Spell it out for me.
>bubble(a[], n);
Where are you getting n? Also, the brackets aren't needed for a function argument, just the array name.
>printf("%d", a[]);
This won't print anything useful, and it's actually pretty unsafe. Then again, it won't compile because of the brackets so what you have here is the ultimate security feature.
>getch();
This isn't needed. If you're willing to force the user to hit Return instead of any key then you can use getchar and not suffer from a non-portable program. Since "Press any key" usually results in the user hitting Return anyway, not much is lost.
>void bubble(int a[]; int n)
Comma?
>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]);
This is strictly my personal preference, but if the body of a conditional or loop is longer than one line (including comments), I use braces. That would turn your loop into this:
Code:
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]);
}
}
Finally, consistency in your formatting is of the utmost importance. Even if you don't care, take the time to make sure that your formatting is consistent throughout the program.
Here's a potential reworking so that you can compare and contrast:
Code:
#include <stdio.h>
#define length(a) (sizeof (a) / sizeof *(a))
void jsw_swap ( int *a, int *b );
void jsw_bubblesort ( int array[], int n );
void jsw_display ( int array[], int n );
int main ( void )
{
int a[] = {7, 3, 66, 3, -5, 22, -77, 2};
printf ( "Original: " );
jsw_display ( a, length ( a ) );
jsw_bubblesort ( a, length ( a ) );
printf ( "Sorted: " );
jsw_display ( a, length ( a ) );
getchar();
return 0;
}
void jsw_swap ( int *a, int *b )
{
int save = *a;
*a = *b;
*b = save;
}
void jsw_bubblesort ( int array[], int n )
{
int i, j;
for ( i = 0; i < n - 1; ++i ) {
for ( j = n - 1; i < j; --j ) {
if ( array[j - 1] > array[j] )
jsw_swap ( &array[j - 1], &array[j] );
}
}
}
void jsw_display ( int array[], int n )
{
int i;
for ( i = 0; i < n; ++i )
printf ( "%d ", array[i] );
printf ( "\n" );
}