Advertisement
minnera

#30daysofcode #day20

Oct 26th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.20 KB | None | 0 0
  1. // https://www.hackerrank.com/challenges/30-sorting/
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. class Solution {
  8.  
  9.     static void Main(String[] args) {
  10.         int n = Convert.ToInt32(Console.ReadLine());
  11.         string[] a_temp = Console.ReadLine().Split(' ');
  12.         int[] a = Array.ConvertAll(a_temp,Int32.Parse);
  13.  
  14.         // Write Your Code Here
  15.         int numSwaps = 0;
  16.         for (int i = 0; i < n; i++) {
  17.             // Track number of elements swapped during a single array traversal
  18.             int numberOfSwaps = 0;
  19.    
  20.             for (int j = 0; j < n - 1; j++) {
  21.                 // Swap adjacent elements if they are in decreasing order
  22.                 if (a[j] > a[j + 1]) {
  23.                     //swap(a[j], a[j + 1]);
  24.                     int seged = a[j];
  25.                     a[j] = a[j + 1];
  26.                     a[j + 1] = seged;
  27.                     numberOfSwaps++;
  28.                 }
  29.             }
  30.             numSwaps += numberOfSwaps;
  31.             // If no elements were swapped during a traversal, array is sorted
  32.             if (numberOfSwaps == 0) {
  33.                 break;
  34.             }
  35.         }
  36.  
  37.         Console.WriteLine("Array is sorted in {0} swaps.", numSwaps);
  38.         Console.WriteLine("First Element: " + a[0]);
  39.         Console.WriteLine("Last Element: " + a[n-1]);
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement