C program for Bubble Sort.

bubble-sort.c

Here is a C program to sort the elements of the array in ascending order using Bubble Sort technique:

#include<stdio.h>
#include<conio.h>

#define SIZE 20

void bubble_sort(int arr[]);

void main()
{
	int i,j;
	int array_to_sort[SIZE];
	clrscr();

	//Get the elements of Array
	for(i=0; i<SIZE; i++)
	{
		j = i+1;
		printf("\nEnter element %d: ",j);
		scanf("%d", &array_to_sort[i]);
	}

	//Print the unsorted array.
	printf("\n\nUnsorted elements of Array are: ");	
	for(i=0; i<SIZE; i++)
	{
		printf("%d ",array_to_sort[i]);
	}

	//Sort array.
	bubble_sort(array_to_sort);

	//Print the sorted array.
	printf("\n\nSorted elements of Array are: ");	
	for(i=0; i<SIZE; i++)
	{
		printf("%d ",array_to_sort[i]);
	}

	getch();
}

//Logic for Bubble Sort.
void bubble_sort(int arr[])
{
	int i,j,temp,swapped;

	for(i=1; i<SIZE; i++)
	{
		swapped = 0;
		for(j=0; j<SIZE-i; j++)
		{
			if(arr[j] > arr[j+1])
			{
				//Swap the elements
				temp = arr[j];
				arr[j] = arr[j+1];
				arr[j+1] = temp;
				swapped = 1;
			}
		}

		//For optimization purpose.
		if(swapped == 0)
		{
			break;
		}
	}
}