In Bubble sort, two consecutive elements in a given list are compared and their positions in the given list (array) are interchanged in ascending or descending order as desired. Consider the following series of numbers, which are to be arranged in ascending or descending order. The series of numbers to be arranged are presented in the form of an array. The input array has the following form:
The process of sequentially visiting all or some of the elements is called a pass. In Bubble sort, arranging n elements requires (n-1) passes. In case the numbers are to be arranged in ascending order, at the end of one pass, the largest number is moved to the last position i.e. bubbles up the largest number. Taking this as the new series and excluding the largest number repeat the process until all the numbers in the series are arranged in ascending order. The Bubble sort is also given the name Interchange or Sinking sort.
C++ program illustrates sorting 5 numbers in ascending order using Bubble sort.
cout<<"Enter the number of values to be sorted ";
cout<<"\nEnter the values ";
cout<<"The list to be sorted is ";
cout<<"Pass "<<i+1<<" ";
Input and Output:
Enter the number of values to be sorted 5
Enter the values 34 22 49 10 67
The list to be sorted is 342249 1067
Pass 1:2234 104967
Pass 2:22 10344967
Pass 3:10 22 34 49 67
Pass 4:10 22 34 49 67
Pass 5:10 22 34 49 67