×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang sort Package

Golang | sort Package: Here, we are going to learn about the Golang sort package and its functions with examples.

The term sorting (sort) is arranging elements in an ordered sequence that can be ascending or descending. In computer science, there are many algorithms to perform the sorting on various kinds of data like merge sort, quick sort, selection sort, bubble sort, etc.

In Go language, the sort package implements sorting for built-in types and user-defined types. The sort package has a variety of functions related to sorting, checking whether a slice is already sorted or not, etc.

To use these sort package functions – we need to import the sort package.

Golang sort Package Functions

The sort package has the following function,

Functions

Function Description
sort.Float64s() It sorts a given slice of float64s (float64 type of elements) in increasing order (ascending order).
sort.Float64sAreSorted() It checks whether the given slice of float64s (float64 type of elements) is sorted in increasing order or not, with NaN values before any other values.
sort.Ints() It sorts a given slice of Ints (int type of elements) in increasing order (ascending order).
sort.IntsAreSorted() It checks whether the given slice of Ints (int type of elements) is sorted in increasing order or not.
sort.IsSorted() It checks whether the given data (interface type) is sorted or not.
sort.Search() It searches and returns the smallest index i in [0, n) at which f(i) is true. The Search() function uses binary search to search an element.
sort.SearchFloat64s() It searches for the given element (x) in a sorted slice of float64s and returns the index as specified by Search.
sort.SearchInts() It searches for the given element (x) in a sorted slice of ints and returns the index as specified by Search.
sort.SearchStrings() It searchs for the given element (x) in a sorted slice of strings and returns the index as specified by Search.
sort.Slice() It sorts the slice x given the provided less function. It may create panic if x is not a slice. Where x is an interface and less is a function.
sort.SliceIsSorted() It checks whether the slice x is sorted according to the provided less function.
sort.SliceStable() It sorts the slice x given the provided less function, keeping equal elements in their original order. It may create panic if x is not a slice. Where x is an interface and less is a function.
sort.Sort() It sorts the data (interface). It makes one call to data.Len to determine n and O(n*log(n)) calls to data.Less and data.Swap. The sort is not guaranteed to be stable.
sort.Stable() It sorts the data (interface), keeping equal elements in their original order. It makes one call to data.Len to determine n, O(n*log(n)) calls to data.Less and O(n*log(n)*log(n)) calls to data.Swap.
sort.Strings() It sorts a given slice of Strings (string type of elements) in increasing order (ascending order).
sort.StringsAreSorted() It checks whether the given slice of strings (string type of elements) is sorted in increasing order or not.

Example of sort.Sort() function

// Golang program to demonstrate the
// example of sort.Sort() Function

package main

import (
	"fmt"
	"sort"
)

type Product struct {
	Name  string
	Qty   int
	Price float64
}

type SortedByPrice []Product

func (s SortedByPrice) Len() int {
	return len(s)
}

func (s SortedByPrice) Less(i, j int) bool {
	return s[i].Price < s[j].Price
}

func (s SortedByPrice) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func main() {
	prd := []Product{
		{"Induction", 100, 4999.99},
		{"Oven", 150, 5000.00},
		{"Refrigerator", 50, 15900.00},
		{"Toaster", 200, 999.00},
	}

	fmt.Println("Before sorting...")
	fmt.Println(prd)

	// Sorting by Name
	sort.Sort(SortedByPrice(prd))

	fmt.Println("After sorting...")
	fmt.Println(prd)
}

Output:

Before sorting...
[{Induction 100 4999.99} {Oven 150 5000} {Refrigerator 50 15900} {Toaster 200 999}]
After sorting...
[{Toaster 200 999} {Induction 100 4999.99} {Oven 150 5000} {Refrigerator 50 15900}]

Example of sort.Strings() function

// Golang program to demonstrate the
// example of sort.Strings() Function

package main

import (
	"fmt"
	"sort"
)

func main() {
	x := []string{"Banana", "Apple", "Cat", "Mango"}
	// Printing x, type, sorting status
	fmt.Println("x:", x)
	fmt.Printf("%T, %v\n", x, sort.StringsAreSorted(x))

	// Sorting x
	sort.Strings(x)

	// Printing x, type, sorting status
	fmt.Println("x:", x)
	fmt.Printf("%T, %v\n", x, sort.StringsAreSorted(x))

	fmt.Println()

	x = []string{"Tigor", "Venue", "City", "Creta"}

	// Printing x, type, sorting status
	fmt.Println("x:", x)
	fmt.Printf("%T, %v\n", x, sort.StringsAreSorted(x))

	// Sorting x
	sort.Strings(x)

	// Printing x, type, sorting status
	fmt.Println("x:", x)
	fmt.Printf("%T, %v\n", x, sort.StringsAreSorted(x))
}

Output:

x: [Banana Apple Cat Mango]
[]string, false
x: [Apple Banana Cat Mango]
[]string, true

x: [Tigor Venue City Creta]
[]string, false
x: [City Creta Tigor Venue]
[]string, true


Comments and Discussions!

Load comments ↻





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