insertion sort in-place code example

Example 1: insertion sort

def insertionSort(arr): 
    for i in range(1, len(arr)): 
        key = arr[i] 
        j = i-1
        while j >= 0 and key < arr[j] : 
                arr[j + 1] = arr[j] 
                j -= 1
        arr[j + 1] = key

Example 2: Insertion sort algorithm

INSERTION-SORT(A)
   for i = 1 to n
   	key ← A [i]
    	j ← i – 1
  	 while j > = 0 and A[j] > key
   		A[j+1]A[j]
   		j ← j – 1
   	End while 
   	A[j+1] ← key
  End for

Example 3: insertion sort

function insertionSortRicorsivo(array A, int n)
     if n>1
        insertionSortRicorsivo(A,n-1)
        value ← A[n-1]
        j ← n-2
        while j >= 0 and A[j] > value 
         do A[j + 1]A[j]
            j ← j-1
        A[j+1] ← value

Tags:

Java Example