Thanks to visit codestin.com
Credit goes to github.com

Skip to content

401JS class 26 Insertion Sort

KD edited this page Mar 17, 2020 · 7 revisions

Insertion Sort: Class 26 Code Challenge blog

InsertionSort(int[] arr)
  
    FOR i = 1 to arr.length
    
      int j <-- i - 1
      int temp <-- arr[i]
      
      WHILE j >= 0 AND temp < arr[j]
        arr[j + 1] <-- arr[j]
        j <-- j - 1
        
      arr[j + 1] <-- temp

Input Array: [8,4,23,42,16,15]

Pass 1

The For loop is initiated with i = 1, j is set to 0 (i-1), and temp is set 4 (arr[i]). In the While loop the number 8 at index 0 is greater than 4, 8 is placed into index 1 and j is set to -1. This while loop ends and 4 (temp) is placed in index 0.

j i arr[j] temp arr
0 1 8 4 [4,8,23,42,16,15]

pass 2

In the for loop i = 2, j is set to 1, and temp is set 23. In the While loop 23 is greater than 8 so the loop is terminated. The value in temp is assigned to arr[j+1] aka arr[i] (it doesn't move).

j i arr[j] temp arr
1 2 8 23 [4,8,23,42,16,15]

pass 3

In the for loop i = 3, j is set to 2, and temp is set 42. In the While loop 42 is greater than 23 so the loop is terminated.

j i arr[j] temp arr
2 3 23 42 [4,8,23,42,16,15]

pass 4

In the for loop i = 4, j is set to 3, and temp is set 16. In the While loop 42 at index 3 is greater than 16, 42 is placed into index 4 and j is set to 2. The number 23 at index 2 is greater than 16, 23 is placed into index 3. The while loop ends with 16 greater than 8. The number 16 (temp) is placed at index 2.

j i arr[j] temp arr
3 4 42 16 [4,8,23,16,42,15]
2 4 23 16 [4,8,16,23,42,15]

pass 5

j i arr[j] temp arr
4 5 42 15 [4,8,23,16,15,42]
3 5 23 15 [4,8,16,15,23,42]
2 5 16 15 [4,8,15,16,23,42]

Efficency

  • Time O(n^n). looping through the array n times .
  • Space O(1). the arr is sorted in place and the value being sorted is held until it is placed.
Clone this wiki locally