Advertisement
Hazem3529

insertion sort

Nov 15th, 2015
426
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.20 KB | None | 0 0
  1. using System;
  2. public class InsertionSortTest
  3. {
  4.     public static void Main(string[] args)
  5.     {
  6.  
  7.        int []arr= {8,2,9,1,5,38,11,88,5};
  8.        sortArray(arr);
  9.        for (int i = 0; i < arr.Length; i++)
  10.        {
  11.            Console.WriteLine(arr[i]);
  12.        }
  13.        
  14.  
  15.     }
  16.  
  17.     static void sortArray(int[] arr)
  18.     {
  19.         int key; //3chan a7ot feh kemet element bt3y ely h3mlo sort
  20.         for (int j = 1; j <arr.Length; j++)
  21.         {  //bfard en el arr[0] aslun sorted fa bbd2 btany element
  22.             key = arr[j];
  23.             int i = j - 1; //3la tool btshwar 3la element ely ablo 3cahn t3ml mokrnat bly abl kollhm
  24.             //low i akbr min zero y3ny mwsltsh ll a5r el array wl arr[i] akbr mn lkey ly m3ya b5ly ely array of i yt7rk lodam
  25.             //howa keda hms7 el value bt3t el j bass ana asln wa5d mnha copy fl key 3cahn h7toha fe mknha lsa7 b3deen
  26.             while (i>= 0 && arr[i]>key)
  27.             {
  28.                 arr[i + 1] = arr[i]; // by3ml shift
  29.                 i--; //b3d keda ashof element ely ablo l7ad ma awsl lnhyt al array
  30.             }
  31.             arr[i + 1] = key; //la7d ya b2a feh mkan fady ll element ly sorted y7t feh  
  32.         }
  33.  
  34.  
  35.        
  36.  
  37.    
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement