Golang program to sort an integer array in descending order using insertion sort

Here, we are going to learn how to sort an integer array in descending order using insertion sort in Golang (Go Language)?
Submitted by Nidhi, on March 07, 2021 [Last updated : March 03, 2023]

Sorting an integer array in descending order using insertion sort in Golang

Problem Solution:

In this program, we will read an array element from the user then sort the array in descending order using insertion sort and then print the sorted array on the console screen.

Program/Source Code:

The source code to sort an integer array in descending order using insertion sort is given below. The given program is compiled and executed successfully.

Golang code to sort an integer array in ascending order using insertion sort

// Golang program to sort an integer array in
// descending order using insertion sort

package main

import "fmt"

func main() {
	var arr [5]int
	var item int = 0
	var flag int = 0
	fmt.Printf("Enter array elements: \n")
	for i := 0; i <= 4; i++ {
		fmt.Printf("Elements: arr[%d]: ", i)
		fmt.Scanf("%d", &arr[i])
	}

	for i := 0; i <= 4; i++ {
		item = arr[i]
		flag = 0
		for j := i - 1; j >= 0 && flag != 1; {
			if item > arr[j] {
				arr[j+1] = arr[j]
				j = j - 1
				arr[j+1] = item
			} else {
				flag = 1
			}
		}
	}

	fmt.Printf("Array after sorting: \n")
	for i := 0; i <= 4; i++ {
		fmt.Printf("%d ", arr[i])
	}
}

Output:

Enter array elements:
Elements: arr[0]: 12
Elements: arr[1]: 3
Elements: arr[2]: 4
Elements: arr[3]: 55
Elements: arr[4]: 61
Array after sorting:
61 55 12 4 3

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

In the main() function, we created an array arr and also created two variables item, flag.

  fmt.Printf("Enter array elements: \n")
    for i:=0;i<=4;i++{
        fmt.Printf("Elements: arr[%d]: ",i)
        fmt.Scanf("%d",&arr[i])
    }

In the above code, we read array elements from the user.

for i:=0; i<=4; i++{
        item=arr[i]
        flag=0
        for j:=i-1;(j>=0 && flag!=1);{
            if(item>arr[j]){
                arr[j+1]=arr[j]
                j=j-1
                arr[j+1]=item
            }else{
                flag=1
            }
        }
    }

In the above code, we applied insertion sort to arrange array elements in descending order. After that, we printed the sorted array on the console screen.

Golang Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.