What is Bubble Sort ?
Bubble sort is the way of sorting the numeric elements in the collection by traversing through the collection and comparing adjacent elements. The collection is traversed from the beginning. The 1st place element is compared with the 2nd place element and if 1st place element is found to be greater than the 2nd place element then both are swapped (i.e. 2nd place element is moved to the 1st place and 1st place element is moved to 2nd place) and if the pair is already in sorted order then the comparison is done between 2nd place element and 3rd place element, here also swapping is done in case 2nd place element is greater than 3rd place element else the comparison moves to 3rd place element and 4th place element, and this way the comparison moves along throughout the collection between adjacent elements.
The name "bubble" because, the every-time the collection is traversed and comparisons takes place, the largest element is bubbled out.
Cons:
The approach is too slow and takes lot of time for sorting out the elements in case the collection is very large. Not preferred to use for larger collections.
Note: this code is written in visual studio console application, which accepts input from the user via Console.
Input Format: input is taken in two lines. In the 1st line user specifies the no. of elements in the array and in the 2nd line user specifies the those number of elements(mentioned in the 1st line) separated by single space. e.g.
Input Format:
4
8 3 7 4
Output Format:
Array has taken 4 swaps to get sorted.
Note: this code is written in visual studio console application, which accepts input from the user via Console.
Input Format: input is taken in two lines. In the 1st line user specifies the no. of elements in the array and in the 2nd line user specifies the those number of elements(mentioned in the 1st line) separated by single space. e.g.
Input Format:
4
8 3 7 4
Output Format:
Array has taken 4 swaps to get sorted.
1st smallest Element: 3
Last largest Element: 8
Last largest Element: 8
Bubble Sort in C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { static void Main(String[] args) { int swapNum = 0; int n = Convert.ToInt32(Console.ReadLine()); string[] a_temp = Console.ReadLine().Split(' '); int[] a = Array.ConvertAll(a_temp,Int32.Parse); for(int i=0; i<n;i++) { int temp; for (int j = 0; j < n - 1; j++) { // Swap adjacent elements if they are in decreasing order if (a[j] > a[j + 1]) { //swap(a[j], a[j + 1]); temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; swapNum++; } } // If no elements were swapped during a traversal, array is sorted if (swapNum == 0) { break; } } Console.WriteLine("Array has taken {0} swaps to get sorted.",swapNum); Console.WriteLine("1st smallest Element: {0}",a[0]); Console.WriteLine("Last largest Element: {0}",a[n-1]); } }