📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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]
Comments
Post a Comment
Leave Comment