Home / Programs / Write a C program that uses a function to sort an array of integers using bubble sort algorithm.
Programming Example

Write a C program that uses a function to sort an array of integers using bubble sort algorithm.

👁 2,708 Views
💻 Practical Program
📘 Step by Step Learning
Write a C program that uses a function to sort an array of integers using bubble sort algorithm.

Program Code

#include <stdio.h>

void sort (int [], int);

int main (void)
{
	int i;
	int arr[10] = {3,2,7,0,6,4,9,8,1,5 };
	printf ("The array before the sort:\n");
	for ( i = 0; i < 10; ++i )
		printf ("%i ", arr[i]);
	sort (arr, 10);
	printf ("\n\nThe array after the sort:\n");
	for ( i = 0; i < 10; ++i )
		printf ("%i ", arr[i]);
	return 0;
}


void sort (int a[], int n)
{
	int i, j, temp;
	for ( i = 0; i < n - 1; ++i )
		for ( j = 0; j < n-i-1; ++j )
			if ( a[j] > a[j+1] ) {
				temp = a[j];
				a[j] = a[j+1];
				a[j+1] = temp;
			}
}
 

Output

The array before the sort:
3 2 7 0 6 4 9 8 1 5

The array after the sort:
0 1 2 3 4 5 6 7 8 9
 

Explanation

None

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.