• + 0 comments

    In C#

    class Solution
    {
        public static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine().Trim());
    
            List<int> a = Console.ReadLine().TrimEnd().Split(' ').ToList().Select(aTemp => Convert.ToInt32(aTemp)).ToList();
    
            int totalSwaps = 0;
            // Write your code here
            for (int i = 0; i < n; i++) {
                // Track number of elements swapped during a single array traversal
                int numberOfSwaps = 0;
                
                for (int j = 0; j < n - 1; j++) {
                    // Swap adjacent elements if they are in decreasing order
                    if (a[j] > a[j + 1]) {
                        swap<int>(a, j);
                        numberOfSwaps++;
                    }
                }
                
                // If no elements were swapped during a traversal, array is sorted
                if (numberOfSwaps == 0) {
                    break;
                }
                
                totalSwaps += numberOfSwaps;
            }
            
            Console.WriteLine($"Array is sorted in {totalSwaps} swaps.");
            Console.WriteLine($"First Element: {a[0]}");
            Console.WriteLine($"Last Element: {a[^1]}");
        }
        
        public static void swap<T>(List<T> array, int index)
        {
            var swap1 = array[index];
            var swap2 = array[index + 1];
            
            array[index] = swap2;
            array[index + 1] = swap1;
        }
    }