1. Introduction
In this article, we will learn how to write a Go program to sort the given array in descending order.
2. Program Overview
Steps:
1. Creating a pre-populated array of integers.
2. An implementation of a sorting algorithm to sort an array of integers in descending order.
3. Display the sorted array to the user.
3. Code Program
// Beginning with the declaration of the main package.
package main
// The fmt package for input-output needs.
import "fmt"
// Implementing Bubble Sort to achieve descending order.
func bubbleSortDescending(arr []int) []int {
n := len(arr)
for i := 0; i < n-1; i++ {
for j := 0; j < n-i-1; j++ {
// Altering the comparison to tailor Bubble Sort for descending order.
if arr[j] < arr[j+1] {
arr[j], arr[j+1] = arr[j+1], arr[j]
}
}
}
return arr
}
// The crux, our main function.
func main() {
array := []int{64, 34, 25, 12, 22, 11, 90}
fmt.Println("Original Array:", array)
// The transformation process to descending order.
sortedArray := bubbleSortDescending(array)
fmt.Println("Sorted in Descending Order:", sortedArray)
}
Output:
Upon execution, the program will recite: Original Array: [64 34 25 12 22 11 90] Sorted in Descending Order: [90 64 34 25 22 12 11]
4. Step By Step Explanation
1. Package and Import: As always, we go with package main and the fmt package for printing and formatting.
2. Bubble Sort Descending Mechanism:
- Take the length of the list.
- Go through the list repeatedly using two nested loops.
- In each iteration, compare adjacent numbers.
- Swap numbers if the current one is smaller than the next.
- Repeat until the list is fully sorted in descending order.
3. Main Function:
- Declare an array of numbers: {64, 34, 25, 12, 22, 11, 90}.
- Display the original array.
- Use the bubbleSortDescending function to sort the array.
- Display the array after sorting.
Comments
Post a Comment
Leave Comment