Wednesday, November 01, 2017

Insertion Sort

 var arr = new List<int> { 5,6,1,2,3,1 };// input.ToCharArray().Cast<int>().ToList();
            //Loop length of array - start from second position
            
            //Compare pointer to previous item
            //make smaller to the left untill you reach the beginning of the array

            var currentItem = 0;
            for (int p = 1; p < arr.Count; p++)
            {
                currentItem = arr[p];
                //Loop from current p position to beginning of array - pointing at location of comparison with current item and potential location of currentItem
                //If currentItem is smaller then swap 
                for (int i = p - 1 ; i >= 0; i--)
                {
                    if (currentItem < arr[i])
                    {
                        var temp = arr[i];
                        arr[i] = currentItem;
                        arr[i+1] = temp;
                    } 
                    else
                    {
                        break;
                    }
                }
                
            }

           

No comments: