Program Steps
- 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
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment