BubaLazi

05. Sort Array Using Insertion Sort

Jul 18th, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.17 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ArraysAndLists
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             int[] arr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
  14.             InsertionSort(arr);
  15.             Console.WriteLine(string.Join(" ", arr));
  16.         }        
  17.  
  18.         static void InsertionSort(int[] arr)
  19.         {
  20.             for(int firstIndex = 0; firstIndex < arr.Length; firstIndex++)
  21.             {
  22.                 for(int secondIndex = firstIndex; secondIndex > 0; secondIndex --)
  23.                 {
  24.                     if(arr[secondIndex - 1] > arr[secondIndex])
  25.                     {
  26.  
  27.                         Swap(ref arr[secondIndex - 1], ref arr[secondIndex]);
  28.                     }
  29.                     else
  30.                     {
  31.                         break;
  32.                     }
  33.                 }
  34.             }
  35.         }
  36.  
  37.        
  38.         static void Swap(ref int first,ref int second)
  39.         {
  40.             int temp = first;
  41.             first = second;
  42.             second = temp;
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment