bubble sort in csharp

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. Here is an example of how to implement bubble sort in C#:

main.cs
public static void BubbleSort(int[] array)
{
    int n = array.Length;
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = 0; j < n - i - 1; j++)
        {
            if (array[j] > array[j + 1])
            {
                int temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }
}
369 chars
17 lines

To use the above function to sort an array, you can simply call it like this:

main.cs
int[] arr = { 3, 7, 1, 9, 2, 8, 5 };
BubbleSort(arr);

foreach (int num in arr)
{
    Console.Write(num + " ");
}
114 chars
8 lines

This will output: 1 2 3 5 7 8 9

related categories

gistlibby LogSnag