BubbleSort

mail@pastecode.io avatar
unknown
csharp
25 days ago
977 B
93
Indexable
Never
class BubbleSort
{
    static void Main()
    {
        int[] array = [5, 4, 3, 6, 1, 2, 7, 9, 8, 10];

        BubbleSortAlgorithm(array);

        Console.Write("Sorted array: ");
        foreach (int num in array)
        {
            Console.Write(num + " ");
        }
    }

    static void BubbleSortAlgorithm(int[] arr)
    {
        int n = arr.Length - 1; // Length of the array - 1, 0 based indexing

        for (int i = 0; i < n; i++) // Outer loop to keep track of the number of passes
        {
            for (int j = 0; j < n - i; j++) // Inner loop to compare adjacent elements, keeping track of the unsorted items
            {
                if (arr[j] > arr[j + 1])
                {
                    // Swap elements if they are in the wrong order
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}
Leave a Comment