TheBulgarianWolf

BubbleSort Hackerrank

May 30th, 2021
992
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. using System.CodeDom.Compiler;
  2. using System.Collections.Generic;
  3. using System.Collections;
  4. using System.ComponentModel;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Runtime.Serialization;
  11. using System.Text.RegularExpressions;
  12. using System.Text;
  13. using System;
  14.  
  15.  
  16.  
  17. class Solution
  18. {
  19.     public static void Main(string[] args)
  20.     {
  21.         int n = Convert.ToInt32(Console.ReadLine().Trim());
  22.  
  23.         List<int> a = Console.ReadLine().TrimEnd().Split(' ').ToList().Select(aTemp => Convert.ToInt32(aTemp)).ToList();
  24.         int countSwaps = 0;
  25.         for(int j = 0;j<a.Count;j++){
  26.            
  27.             for(int i = 0;i<a.Count-1;i++){
  28.                 if(a[i] > a[i+1]){
  29.                     int first = a[i];
  30.                     int second = a[i+1];
  31.                     a.RemoveAt(i);
  32.                     a.Insert(i, second);
  33.                     a.RemoveAt(i+1);
  34.                     a.Insert(i+1, first);
  35.                     countSwaps++;
  36.                 }
  37.            
  38.             }
  39.             if(countSwaps == 0){
  40.                 break;
  41.             }
  42.         }
  43.         Console.WriteLine("Array is sorted in {0} swaps.",countSwaps);
  44.         Console.WriteLine("First Element: " + a[0]);
  45.         Console.WriteLine("Last Element: " + a[a.Count-1]);
  46.         // Write your code here
  47.     }
  48. }
Add Comment
Please, Sign In to add comment