Advertisement
grubcho

Insertion sort with List - Algorithms

Jun 29th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 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 insertion_sort_with_list
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             List<int> list = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
  14.  
  15.             List<int> resultList = InsertionSort(list);
  16.             Console.WriteLine(string.Join(" ", resultList));
  17.         }
  18.         static List<int> InsertionSort(List<int> list)
  19.         {
  20.             List<int> resultList = new List<int>();
  21.             for (int firstIndex = 0; firstIndex < list.Count; firstIndex++)
  22.             {
  23.                 bool isInserted = false;
  24.                 int currentElementToInsert = list[firstIndex];
  25.                 for (int secondIndex = 0; secondIndex < resultList.Count; secondIndex++)
  26.                 {
  27.                     int currentResultListElement = resultList[secondIndex];
  28.                     if (currentElementToInsert < currentResultListElement)
  29.                     {
  30.                         resultList.Insert(secondIndex, currentElementToInsert);
  31.                         isInserted = true;
  32.                         break;
  33.                     }
  34.                 }
  35.                 if (!isInserted)
  36.                 {
  37.                     resultList.Add(currentElementToInsert);
  38.                 }
  39.             }
  40.             return resultList;
  41.         }        
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement