1. Introduction
Sorting is a process that arranges elements in a particular order. Sorting arrays, specifically in ascending order, is fundamental in a myriad of applications, be it in data analytics, database systems, or even in our day-to-day tasks like organizing contacts. While Go offers built-in slice sorting, there's merit in understanding the basics. This blog post will take you on a journey through a Go program that sorts an array in ascending order from the ground up.
2. Program Overview
Our bespoke Go program will:
1. Create an array with numbers.
2. Implement a sorting algorithm to align these numbers in ascending order.
3. Showcase the freshly sorted array to the user.
3. Code Program
// The main package declaration.
package main
// The trusty fmt package is marshaled for our I/O maneuvers.
import "fmt"
// Our sorting function, using the timeless Bubble Sort algorithm.
func bubbleSort(arr []int) []int {
n := len(arr)
for i := 0; i < n-1; i++ {
for j := 0; j < n-i-1; j++ {
if arr[j] > arr[j+1] {
// A classic swap maneuver.
arr[j], arr[j+1] = arr[j+1], arr[j]
}
}
}
return arr
}
// The epicenter of our program, the main function.
func main() {
array := []int{64, 34, 25, 12, 22, 11, 90}
fmt.Println("Original Array:", array)
// The array undergoes the sorting process.
sortedArray := bubbleSort(array)
fmt.Println("Sorted Array:", sortedArray)
}
Output:
The program, upon its noble execution, will exclaim: Original Array: [64 34 25 12 22 11 90] Sorted Array: [11 12 22 25 34 64 90]
Comments
Post a Comment
Leave Comment