kidroca

Selection Sort with IndexOfMin Extension Method

May 13th, 2016
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.30 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class SelectionSort
  5. {
  6.     private static void Main(string[] args)
  7.     {
  8.         int n = int.Parse(Console.ReadLine());
  9.         int[] A = new int[n];
  10.  
  11.         for (int i = 0; i < A.Length; i++)
  12.         {
  13.             A[i] = int.Parse(Console.ReadLine());
  14.         }
  15.  
  16.         for (int i = 0; i < A.Length; i++)
  17.         {
  18.  
  19.             Swap(A, i, A.IndexOfMin(i));
  20.             Console.WriteLine(A[i]);
  21.         }
  22.     }
  23.  
  24.     private static void Swap(IList<int> list, int first, int second)
  25.     {
  26.         int temp = list[first];
  27.         list[first] = list[second];
  28.         list[second] = temp;
  29.     }
  30. }
  31.  
  32. public static class CollectionExtensions
  33. {
  34.     public static int IndexOfMin<T>(this IList<T> collection, int startIndex = 0)
  35.         where T : IComparable<T>
  36.     {
  37.         if (0 > startIndex || startIndex >= collection.Count)
  38.         {
  39.             throw new IndexOutOfRangeException("Start index is outside the bounds of the collection");
  40.         }
  41.  
  42.         int minIndex = startIndex;
  43.  
  44.         for (int i = startIndex; i < collection.Count; i++)
  45.         {
  46.             if (collection[i].CompareTo(collection[minIndex]) < 0)
  47.             {
  48.                 minIndex = i;
  49.             }
  50.         }
  51.  
  52.         return minIndex;
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment