Advertisement
earlution

InsertionSort

Nov 6th, 2023 (edited)
627
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.10 KB | None | 0 0
  1. // C# program for implementation of Insertion Sort
  2. using System;
  3.  
  4. class InsertionSort {
  5.  
  6.     // Function to sort array
  7.     // using insertion sort
  8.     void sort(int[] arr)
  9.     {
  10.         int n = arr.Length;
  11.         for (int i = 1; i < n; ++i) {
  12.             int key = arr[i];
  13.             int j = i - 1;
  14.  
  15.             // Move elements of arr[0..i-1],
  16.             // that are greater than key,
  17.             // to one position ahead of
  18.             // their current position
  19.             while (j >= 0 && arr[j] > key) {
  20.                 arr[j + 1] = arr[j];
  21.                 j = j - 1;
  22.             }
  23.             arr[j + 1] = key;
  24.         }
  25.     }
  26.  
  27.     // A utility function to print
  28.     // array of size n
  29.     static void printArray(int[] arr)
  30.     {
  31.         int n = arr.Length;
  32.         for (int i = 0; i < n; ++i)
  33.             Console.Write(arr[i] + " ");
  34.  
  35.         Console.Write("\n");
  36.     }
  37.  
  38.     // Driver Code
  39.     public static void Main()
  40.     {
  41.         int[] arr = { 12, 11, 13, 5, 6 };
  42.         InsertionSort ob = new InsertionSort();
  43.         ob.sort(arr);
  44.         printArray(arr);
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement