Bubble Sort in C# : Learn the Basics

Bubble Sort in C# – Learn the Basics

Bubble sort is one of the most basic sorting algorithms in programming. It repeatedly compares and swaps adjacent values to sort the entire array. This makes it a great starting point for beginners learning algorithms.

What is Bubble Sort?

Bubble sort compares two adjacent values and swaps them if they are in the wrong order. After each full pass through the array, the largest unsorted value "bubbles up" to its correct position at the end. This process is repeated until the whole array is sorted.

Bubble Sort in C# – Learn the Basics

Steps

  • Start from the leftmost element
  • Compare each pair of adjacent elements
  • Swap them if they are in the wrong order
  • Repeat for all elements, ignoring the last sorted ones in each iteration

C# Code Example (Traditional Swap)

int[] numbers = { 52, 86, 3, 79, 45, 12, 99, 23, 56, 78 };

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

Console.WriteLine(string.Join(", ", numbers));

Tuple Swap in C#

C# supports tuple deconstruction syntax introduced in version 7.0. It allows swapping two values in a single line without a temporary variable:

(numbers[j], numbers[j + 1]) = (numbers[j + 1], numbers[j]);

This method is concise, readable, and widely used in modern C# code.

Using string.Join() for Output

To print the sorted array, string.Join() can be used instead of a loop. It takes a separator and an array, returning a formatted string:

Console.WriteLine(string.Join(", ", numbers));

This prints the array elements in one line, separated by commas.

Summary

Bubble sort is simple but inefficient for large datasets. However, it’s perfect for understanding how basic sorting works. In the next post, we’ll explore Selection Sort, another fundamental algorithm that takes a different approach to sorting.

Popular posts from this blog

Understanding Arrays as Reference Types in C#

Setting Up a Basic Follow Camera with Cinemachine 3.x

How to Initialize Struct – C# Struct Initialization Guide