Program Structure
The following Go program implements the insertion sort algorithm, which sorts an array of integers in ascending order. The insertion sort algorithm works by building a sorted portion of the array one element at a time. It repeatedly takes the next element from the unsorted portion and inserts it into the correct position in the sorted portion.
Go Code Implementation
package main
import (
"fmt"
)
// insertionSort sorts an array of integers using the insertion sort algorithm.
func insertionSort(arr []int) {
// Iterate over the array from the second element.
for i := 1; i < len(arr); i++ { key := arr[i] // Element to be positioned. j := i - 1 // Last index of the sorted portion. // 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--
}
arr[j+1] = key // Place key at its correct position.
}
}
func main() {
// Sample array to be sorted.
arr := []int{64, 34, 25, 12, 22, 11, 90}
fmt.Println("Unsorted array:", arr)
// Call the insertionSort function to sort the array.
insertionSort(arr)
fmt.Println("Sorted array:", arr)
}
Explanation of the Code
- Package Declaration: The program starts with the
package maindeclaration, indicating that this is the main package of the Go application. - Import Statement: The
fmtpackage is imported for formatted I/O operations. - insertionSort Function: This function takes a slice of integers as input and sorts it in-place using the insertion sort algorithm.
- It uses a loop starting from the second element (index 1) to the end of the array.
- The key element to be inserted into the sorted portion is stored in the variable
key. - Another loop shifts elements in the sorted portion to make space for the key.
- The key is placed at its correct position in the sorted portion.
- Main Function: This is the entry point of the program where the unsorted array is defined, printed, sorted using
insertionSort, and then printed again.
How to Run the Program
To run this program, follow these steps:
- Ensure you have Go installed on your machine.
- Create a new file named
insertion_sort.goand copy the code into this file. - Open a terminal and navigate to the directory where the file is saved.
- Run the command
go run insertion_sort.goto execute the program.

