# bubble function

This is a discussion on bubble function within the C Programming forums, part of the General Programming Boards category; i have a problem with a homework assignment that i was given. the first part of the assignment asks me ...

1. ## bubble function

i have a problem with a homework assignment that i was given. the first part of the assignment asks me to do a program that uses the bubble funtion to sort an array of interger. so this is the program that i did

----------------------------------------------------------
void bubble_sort ( int a[], int n );
void test_sort ( int n );
void print ( int a[], int n );

#include<stdio.h>

int main ( void )
{
int n;

printf("Testing bubble sort on digits\n");
printf("Give the number of elements : ");
scanf("%d", &n);

test_sort(n);

return 0;
}

static void swap ( int *p, int *q)
{
int tmp = *p;
*p = *q;
*q = tmp;
}

void bubble_sort ( int a[], int n )
{
int i,j;

for (i=0; i<n-1; i++)
{
for (j=n-1; j>i; j--)
if (a[j-1] > a[j])
swap(&a[j-1],&a[j]);

printf("Array after pass %d : \n", i+1);
print(a,n);
}
}

void test_sort ( int n )
{
int a[n];
int i,num;

for (i=0; i<n; i++)
{
printf("Give %d integers\n",n);
printf(" give integer number %d: ",i+1);scanf("%d",&num);
a[i] = num;
}

printf("The %d numbers before sorting :\n", n);
print(a,n);

bubble_sort(a,n);

printf("The %d numbers after sorting :\n", n);
print(a,n);
}

void print ( int a[], int n )
{
int i;

for (i=0; i<n; i++)
printf(" %d", a[i]);

printf("\n");
}

-------------------------------
the second part of the problem asks me to modify the bubble function so that it terminates after the first pass in which no two elements are interchanged. i do not understand what are they trying to say by this. if anybody can help or explain what they probably mean, it will be greatly appreciated.

2. > to modify the bubble function so that it terminates after the first pass in which no two elements are interchanged.
The inner loop looks like this
Code:
```int sorted = 1;
for (j=n-1; j>i; j--) {
if (a[j-1] > a[j]) {
swap(&a[j-1],&a[j]);
sorted = 0;
}
}
if ( sorted ) break;```
Basically, if you make it through without swapping, sorted remains at 1, and hence exits from the sort.