Bubble sort

Bubble sort

Bubble sort is the simplest sorting algorithm that works by repeatedly replacing adjacent items if they are in the wrong order.

Example: Input – (75 21 54 32 88)

First pass:

(75 21 54 32 88) -> (21 75 54 32 88), here the algorithm compares the first two elements and swaps if 75 > 21.
(21 75 54 32 88) -> (21 54 75 32 88), Swap if 75 > 54
(21 54 75 32 88) -> (21 54 32 75 88), Swap if 75 > 32
(21 54 32 75 88) -> (21 54 32 75 88), Now because these items are already okay 88 > 75,
the algorithm does not swap them.

Second pass:

(21 54 32 75 88) -> (21 54 32 75 88)
(21 54 32 75 88) -> (21 32 54 75 88), Swap 54 > 32
(21 32 54 75 88) -> (21 32 54 75 88)
(21 32 54 75 88) -> (21 32 54 75 88)
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third pass:

(21 32 54 75 88) -> (21 32 54 75 88)
(21 32 54 75 88) -> (21 32 54 75 88)
(21 32 54 75 88) -> (21 32 54 75 88)
(21 32 54 75 88) -> (21 32 54 75 88)

Implementation in C# code

public class Program
{
   public static void Main()
   {
       int[] arr = { 79, 86, 97, 43, 64, 25, 12, 22, 11, 7, 23, 5 };

	BubbleSort(arr);
	Console.WriteLine("Sorted array");
	PrintArray(arr);
   }

   static void BubbleSort(int[] arr)
   {
      int n = arr.Length;

      for (int i = 0; i < n - 1; i++)
         for (int j = 0; j < n - i - 1; j++)
	    if (arr[j] > arr[j + 1])
	    {
	        int temp = arr[j];
		arr[j] = arr[j + 1];
		arr[j + 1] = temp;
	    }
   }

   static void PrintArray(int[] arr)
   {
      int n = arr.Length;

      for (int i = 0; i < n; ++i)
	 Console.Write(arr[i] + " ");

      Console.WriteLine();
   }
}

Output

5 7 11 12 22 23 25 43 64 79 86 97 

​When can we adopt

Due to its simplicity, bubble sort is often used to introduce the concept of a sort algorithm. In computer graphics, it is popular for its ability to detect very small errors, such as replacing only two elements in almost sorted arrays.

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *