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

C Programming Language / Function in C Language

2624

Program:

#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

This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.