Q:

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

belongs to collection: Golang Array Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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

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

package main

import "fmt"

func main() {
	var arr [5]int
	var min int = 0
	var temp 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++ {
		min = i
		for j := i + 1; j <= 4; j++ {
			if arr[j] > arr[min] {
				min = j
			}
		}
		temp = arr[i]
		arr[i] = arr[min]
		arr[min] = temp
	}

	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]: 45
Elements: arr[2]: 6
Elements: arr[3]: 15
Elements: arr[4]: 61
Array after sorting:
61 45 15 12 6

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 mintemp.

  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++{
    min=i
    for j:=i+1;j<=4;j++{
        if(arr[j]>arr[min]){
            min=j
        }
    }
    temp=arr[i]
    arr[i]=arr[min]
    arr[min]=temp
}

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang program to add two integer arrays... >>
<< Golang program to sort an integer array in ascendi...