Bubble Sort Algorithm in C#

1. Introduction

The Bubble Sort algorithm is one of the simplest sorting algorithms in computer science. It works by repeatedly swapping adjacent elements if they are in the wrong order until the list is sorted. While it is not the most efficient sorting algorithm for large datasets, it serves as a great starting point for understanding basic sorting concepts.

2. Implementation Steps

1. Start iterating from the first element of the array.

2. Compare the current element with the next element.

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

4. Continue the process for each element until no more swaps are needed, indicating that the array is sorted.

3. Implementation in C#

using System;
public class BubbleSort {
    public static void Sort(int[] arr) {
        int length = arr.Length;
        for (int i = 0; i < length - 1; i++) {
            for (int j = 0; j < length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // Swap arr[j] and arr[j+1]
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}
public class Program {
    public static void Main() {
        int[] arr = {64, 34, 25, 12, 22, 11, 90};
        Console.WriteLine("Unsorted array:");
        foreach (var item in arr) {
            Console.Write(item + " ");
        }
        BubbleSort.Sort(arr);
        Console.WriteLine("\nSorted array:");
        foreach (var item in arr) {
            Console.Write(item + " ");
        }
    }
}

Output:

Unsorted array:
64 34 25 12 22 11 90
Sorted array:
11 12 22 25 34 64 90

Explanation:

1. The BubbleSort class contains a static method named Sort which sorts an integer array using the bubble sort algorithm.

2. Inside the Sort method, two nested loops iterate through the array.

3. The outer loop (i) runs until one less than the number of items in the array, and the inner loop (j) runs until length - i - 1. This accounts for the fact that with each pass, the largest element will "bubble up" to its correct position, thereby reducing the effective length of the unsorted portion of the array.

4. If the current element (arr[j]) is greater than the next element (arr[j + 1]), they are swapped.

5. The Main method demonstrates the sorting of an integer array using the BubbleSort class. It prints the unsorted and sorted array.