We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
classSolution{publicstaticvoidMain(string[]args){intn=Convert.ToInt32(Console.ReadLine().Trim());List<int>a=Console.ReadLine().TrimEnd().Split(' ').ToList().Select(aTemp=>Convert.ToInt32(aTemp)).ToList();inttotalSwaps=0;// Write your code herefor(inti=0;i<n;i++){// Track number of elements swapped during a single array traversalintnumberOfSwaps=0;for(intj=0;j<n-1;j++){// Swap adjacent elements if they are in decreasing orderif(a[j]>a[j+1]){swap<int>(a,j);numberOfSwaps++;}}// If no elements were swapped during a traversal, array is sortedif(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]}");}publicstaticvoidswap<T>(List<T>array,intindex){varswap1=array[index];varswap2=array[index+1];array[index]=swap2;array[index+1]=swap1;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 20: Sorting
You are viewing a single comment's thread. Return to all comments →
In C#