Insertion Sort is a simple sorting algorithm that is based on the idea of building a sorted sequence one element at a time.
For example, imagine you have a set of playing cards. To sort them, you start with one card and then, one by one, you insert the next card into its proper position relative to those already sorted. By the time you have gone through all the cards, they end up being sorted.
In this blog post, we will learn how to write a Go program to implement insertion sort.
Program Steps
In our Go program, we'll:
- Iterate over the elements of the array.
- For each element, compare it with the previous elements.
- If the current element is smaller than the previous element, we keep comparing until we reach an element smaller or reach the start of the array.
- Insert the element in its correct position.
Code Program
package main
import "fmt"
// Function to perform insertion sort
func insertionSort(arr []int) []int {
for i := 1; i < len(arr); i++ {
key := arr[i]
j := i - 1
// Move elements of arr[0..i-1] that are greater than key
// to one position ahead of their current position
for j >= 0 && arr[j] > key {
arr[j+1] = arr[j]
j = j - 1
}
arr[j+1] = key
}
return arr
}
func main() {
array := []int{12, 11, 13, 5, 6}
fmt.Println("Original Array:", array)
sortedArray := insertionSort(array)
fmt.Println("Sorted Array:", sortedArray)
}
Output:
Original Array: [12 11 13 5 6] Sorted Array: [5 6 11 12 13]
Explanation
Initialization: Start from the second element (consider the first element as sorted).
Comparison: Compare the current element with the previous elements. If the current element is smaller than the previous element, we continue this comparison with the elements before until we reach an element smaller or until we reach the start of the array.
Insertion: Once we find the correct position for the current element, we insert it.
Iteration: Repeat the process for all the elements in the array.
Insertion sort is commonly used when the number of elements is small. It can also be advantageous when the input array is partially sorted and when there is only a small number of elements out of order.
Comments
Post a Comment
Leave Comment