Bubble Sort in C

Previous
Next

Bubble Sort:

  • Simple sorting technique to sort elements in array.
  • We can sort the elements in either ascending order or descending order.
  • In bubble sort, index element always compare with the next element to it and swapping if required.
  • For each pass(loop completion), highest element is bubbled to last location.
  • This process continues until all elements get sorted.
#include<stdio.h>
#include<conio.h>
void bubble_sort(int[] , int);
int main()
{
	int arr[50] , n , i ;
	printf("Enter number of elements : ");
	scanf("%d", &n);

	for( i=0 ; i<n ; i++ )
	{
		arr[i] = rand()%100 ;
	}

	printf("Array elements before sort : \n");
	for( i=0 ; i<n ; i++ )
	{
		printf("%d\t",arr[i]);
	}
	printf("\n\n");

	bubble_sort(arr , n) ;

	printf("Array elements after sort : \n");
	for( i=0 ; i<n ; i++ )
	{
		printf("%d\t",arr[i]);
	}
	printf("\n\n");
	return 0;
}
void bubble_sort(int a[ ], int n)
{
	int i, j, temp;
	for (i=0 ; i<n-1 ; ++i)
	{
		for(j=0 ; j<n-1-i ; ++j)
		{
			if (a[j]>a[j+1])
			{
				temp = a[j+1];
				a[j+1] = a[j];
				a[j] = temp;
			}
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form