w3resource logo


C Programming Exercises

C Exercises: Bubble sort algorithm

Secondary Nav

C Programming Searching and Sorting Algorithm: Exercise-3 with Solution

Write a C program to sort a list of elements using the bubble sort algorithm.
Note: Bubble Sort works by repeatedly swapping the adjacent elements if they are in wrong order.

Pictorial presentation - Bubble sort algorithm :

C programming Bubble sort algorithm

Sample C Code:

#include <stdio.h>
  void main()
  {
  int arr[10];
  int i, j, N, temp;
  /* function  declaration */
  int find_max(int  b[10], int k);
  void exchang(int  b[10], int k);
  printf("\nInput no. of values in the array: ");
  scanf("%d",&N);
 printf("\nInput the elements: ");
  for(i=0; i<N ;  i++)
  {
  scanf("%d",&arr[i]);
  }
  /* Selection sorting  begins */
  exchang(arr,N);
  printf("Sorted  array :\n");
  for(i=0; i< N ;  i++)
  {
  printf("%d\n",arr[i]);
  }
}
/* function to find the maximum value */
  int find_max(int b[10], int k)
  {
  int max=0,j;
  for(j = 1; j <=  k; j++)
  {
  if ( b[j] >  b[max])
  {
  max =  j;
  }
  }
  return(max);
  }
  void exchang(int  b[10],int k)
  {
  int  temp, big, j;
  for ( j=k-1;  j>=1; j--)
  {
  big =  find_max(b,j);
  temp = b[big];
  b[big] = b[j];
  b[j] = temp;
  }
  return;
  }

Flowchart :

Flowchart: C Programming - Bubble sort algorithm

C Code Editor:

#include <stdio.h>
  void main()
  {
  int arr[10];
  int i, j, N, temp;
 /* function  declaration */
  int find_max(int  b[10], int k);
  void exchang(int  b[10], int k);
  printf("\nInput no. of values in the array: ");
  scanf("%d",&N);
  printf("\nInput the elements one by one: ");
  for(i=0; i<N ;  i++)
  {
   scanf("%d",&arr[i]);
  }
  /* Selection sorting  begins */
  exchang(arr,N);
  printf("Sorted  array :\n");
  for(i=0; i< N ;  i++)
  {
  printf("%d\n",arr[i]);
  }
}
/* function to find the maximum value */
  int find_max(int b[10], int k)
  {
  int max=0,j;
  for(j = 1; j <=  k; j++)
  {
  if ( b[j] >  b[max])
  {
  max =  j;
  }
  }
  return(max);
  }
  void exchang(int  b[10],int k)
  {
 int temp, big, j;
  for ( j=k-1;  j>=1; j--)
  {
  big =  find_max(b,j);
  temp = b[big];
  b[big] = b[j];
  b[j] = temp;
  }
  return;
  }

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program