BorislavBorisov

Сортиране Insertion Sort

Feb 6th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.22 KB | None | 0 0
  1. using System;
  2. class InsertionSort
  3. {
  4.     static void Main()
  5.     {
  6.         InsertionSort();
  7.     }
  8.  
  9.     static void InsertionSort()
  10.     {
  11.         Console.Write("\nEnter the total numbers: ");
  12.         int max = int.Parse(Console.ReadLine());
  13.        
  14.         int[] array = new int[max];
  15.         //Input numbers
  16.         for (int i = 0; i < max; i++)
  17.         {
  18.             Console.Write("Enter [" + (i + 1).ToString() + "] element: ");
  19.             array[i] = Convert.ToInt32(Console.ReadLine());
  20.         }
  21.  
  22.         for (int i = 0; i < max; i++)
  23.         {
  24.             int j = i;
  25.             while (j > 0)
  26.             {
  27.                 if (array[j - 1] > array[j])
  28.                 {
  29.                     int temp = array[j - 1];
  30.                     array[j - 1] = array[j];
  31.                     array[j] = temp;
  32.                 }
  33.                 else
  34.                 {
  35.                     break;
  36.                 }
  37.             }
  38.         }
  39.         PrintArray(array);
  40.     }
  41.  
  42.     static void PrintArray(int[] array)
  43.     {
  44.         for (int i = 0; i < array.Length; i++)
  45.         {
  46.             Console.Write("\nSorted [" + (i + 1).ToString() + "] element: ");
  47.             Console.WriteLine(array[i]);
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment