Go - Slice Sorting Example

1. Introduction

Sorting is a fundamental operation in computer science. In Go, slices can be sorted using the sort package, which contains functions for sorting slices of primitive types and user-defined types. This blog post will demonstrate how to sort slices of integers and strings.

Definition

A slice is a segment of an array in Go, which allows for a dynamic size. Sorting a slice involves rearranging the elements in a defined order, typically in ascending or descending.

2. Program Steps

1. Create slices of integers and strings.

2. Sort the slices using the sort package.

3. Print the sorted slices.

3. Code Program

package main

import (
	"fmt"
	"sort"
)

func main() {
	// Step 1: Create slices of integers and strings
	ints := []int{4, 2, 3, 1}
	strs := []string{"c", "a", "b"}

	// Step 2: Sort the slices using the sort package
	sort.Ints(ints)
	sort.Strings(strs)

	// Step 3: Print the sorted slices
	fmt.Println("Sorted ints:", ints)
	fmt.Println("Sorted strings:", strs)
}

Output:

Sorted ints: [1 2 3 4]
Sorted strings: [a b c]

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" and import "sort" - Importing the necessary packages for formatted output and sorting functionality.

3. ints and strs - Slices of int and string are created and initialized with unsorted data.

4. sort.Ints(ints) - Sorts the slice of integers in ascending order.

5. sort.Strings(strs) - Sorts the slice of strings in ascending lexical order.

6. fmt.Println - Prints the sorted slices to verify that the elements are now in order.

7. The output confirms the slices have been sorted as expected.


Comments