Advertisement
desislava_topuzakova

02. Insertion Sort

Jun 14th, 2020
1,023
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.19 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Sortign
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             int[] numbers = Console.ReadLine().Split(" ").Select(int.Parse).ToArray();
  12.             insertionSort(numbers);
  13.             printArray(numbers);          
  14.  
  15.         }
  16.  
  17.         static void insertionSort(int[] arr)
  18.         {
  19.             int n = arr.Length;
  20.             for (int i = 1; i < n; ++i)
  21.             {
  22.                 int key = arr[i];
  23.                 int j = i - 1;
  24.  
  25.                 // Move elements of arr[0..i-1],
  26.                 // that are greater than key,
  27.                 // to one position ahead of
  28.                 // their current position
  29.                 while (j >= 0 && arr[j] > key)
  30.                 {
  31.                     arr[j + 1] = arr[j];
  32.                     j = j - 1;
  33.                 }
  34.                 arr[j + 1] = key;
  35.             }
  36.         }
  37.  
  38.  
  39.         static void printArray(int[] arr)
  40.         {
  41.             int n = arr.Length;
  42.             for (int i = 0; i < n; ++i)
  43.                 Console.Write(arr[i] + " ");
  44.             Console.WriteLine();
  45.         }
  46.  
  47.  
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement