This program is an implementation of Bubble sort algorithm. The program receives unsorted input numbers and sort the number in ascending or descending number as an output.
Visit following link to learn about other sorting and searching algorithms.
This program is written with Turbo C++ version 3 compiler, but you can use any other standard C compiler to code and run this program. It is intended for intermediate to advanced level learner of C language.
To help you understand this program see following sections – Problem definition, Flowchart of the program and a verified output.
In this program we read some numbers into an array. The numbers are unsorted and our goal is to sort the input numbers using Bubble Sort algorithm.,/p>
In depth analysis of the Bubble Sort algorithm is not in the scope of the article. We discuss the working of this algorithm and later implement the same using C program.
The working of this algorithm is easy to understand with an example. Suppose we are given following unsorted numbers to sort using bubble sort.
unsorted = 2 4 1 8 6 Pick the first number = 2
Compare with all the number one-by-one from right-to-left and when a[j] > a[j+1], swap the numbers.
2 1 (swap) The array is now = 1 2 4 8 6
Pick the second number = 2 and it is smaller than all the other numbers.
Pick the third number = 4 and it is found to be smaller the rest of the numbers.
Pick the fourth number = 8,
8 > 6 (swap) The array is now = 1 2 3 4 6 8
Pick the fifth number = 6 to sort and it is again smaller than last number 8. In this way the whole array is sorted.
Program Code Bubble sort
#define N 100
/* Read number of elements in array */
printf("ENTER NUMBER OF ELEMENTS:");
/* Read the elements of array */
printf("ENTER %d ELEMENTS\n",n);
/* Do Bubble Sort */
temp = array[j];
array[j+1] = temp;
/* Print the Sorted Array */
printf("Sorted list in Ascending Order:\n");
Output-Bubble Sort Algorithm
The output of the above program for bubble sort algorithm is given below. The first ask for number of elements and then the elements itself.
The output is sorted number in ascending order. You can modify the program source code to change the order.