Bubble Sort

Bubble Sort is a simple comparison-based sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted.

 
How Bubble Sort Works:

Compare Adjacent Elements:

Start from the first element and compare it with the next element in the array.
 

Swap if Out of Order:

If the current element is greater than the next, swap them.
 

Move to Next Pair:

Move to the next pair of adjacent elements and repeat the comparison and swapping if necessary.
 

Repeat for All Elements:

Continue this process for all elements, reducing the range after each full pass, as the largest elements “bubble” to the end.
 

End Condition:

The algorithm completes when a full pass is made without any swaps, indicating that the array is sorted.
 

 
Time Complexity:

Best Case: O(n), when the array is already sorted (with an optimized version that stops early).

Average Case: O(n²), because the algorithm compares each pair of elements in the array and performs swaps if needed.

Worst Case: O(n²), when the array is in reverse order.

 
Space Complexity:

O(1), because Bubble Sort is an in-place sorting algorithm.
 

 

using System;

public class Bubble_Sort
{
    public static void Main(string[] args)
    {
        int[] a = { 3, 0, 2, 5, -1, 4, 1 };
        int t;
        Console.WriteLine("\nOriginal array: ");
        foreach (int aa in a)
            Console.Write(aa + " ");
        for (int p = 0; p <= a.Length - 2; p++)
        {
            for (int i = 0; i <= a.Length - 2; i++) { if (a[i] > a[i + 1])
                {
                    t = a[i + 1];
                    a[i + 1] = a[i];
                    a[i] = t;
                }
            }
        }
        Console.WriteLine("\n\nSorted array: ");
        foreach (int aa in a)
            Console.Write(aa + " ");
        Console.Write("\n");
        Console.Read();

    }
}