In this tutorial, we’ll explore the implementation of the bubble sort algorithm in C#. Bubble sort is a straightforward sorting algorithm that repeatedly steps through the list, compares adjacent items, and swaps them if they are in the wrong order.
What is Bubble Sort?
Bubble sort is a simple sorting algorithm that operates by comparing and swapping adjacent elements in a list until the entire list is sorted. Although not the most efficient sorting algorithm for large datasets, it serves as a fundamental concept in sorting algorithms.
Bubble Sort Animation
Here’s a visual representation of how the bubble sort algorithm works:
C# Implementation
Now, let’s dive into the C# code for implementing bubble sort. In this example, we’ll create a class named BubbleSort
with a method BubbleSort()
:
using System;
namespace SortingDemo
{
public class BubbleSort
{
public void BubbleSort()
{
// Initialize array data
int[] data = { 5, 3, 6, 1, 8, 7, 2, 4 };
for (int outerIndex = 0; outerIndex < data.Length; outerIndex++)
{
for (int innerIndex = 0; innerIndex < data.Length - 1; innerIndex++)
{
if (data[innerIndex] > data[innerIndex + 1])
{
// Swap data
Swap(data, innerIndex);
}
}
}
}
private static void Swap(int[] data, int innerIndex)
{
int temp = data[innerIndex + 1];
data[innerIndex + 1] = data[innerIndex];
data[innerIndex] = temp;
}
}
}
In the BubbleSort
class, the BubbleSort()
method initializes an array named data
and performs the bubble sort algorithm. The Swap
method is called to interchange elements when necessary.
Related posts
How to Visualize sorting algorithm using Blazor
Bubble sorting an object array in C#