×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang sort.Stable() Function with Examples

Golang | sort.Stable() Function: Here, we are going to learn about the Stable() function of the sort package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 14, 2021

sort.Stable()

The Stable() function is an inbuilt function of the sort package which is used to sort 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.

It accepts a parameter (data Interface) and sorts the data, keeping equal elements in their original order.

Syntax

func Stable(data Interface)

Parameters

  • data : An interface type to be sorted.

Return Value

The Stable() function does not return any value.

Example 1

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

package main

import (
	"fmt"
	"sort"
	"unicode/utf8"
)

type student struct {
	Name string
	Age  int
}

type SortedByName []student

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

func (s SortedByName) Less(i, j int) bool {
	iRune, _ := utf8.DecodeRuneInString(s[i].Name)
	jRune, _ := utf8.DecodeRuneInString(s[j].Name)
	return int32(iRune) < int32(jRune)
}

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

func main() {
	std := []student{
		{"Yashna", 21},
		{"Tanisha", 24},
		{"Carry", 22},
		{"Dev", 34},
		{"Carry", 28},
		{"Dev", 32},
	}

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

	// Sorting by Name
	sort.Stable(SortedByName(std))

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

Output:

Before sorting...
[{Yashna 21} {Tanisha 24} {Carry 22} {Dev 34} {Carry 28} {Dev 32}]
After sorting...
[{Carry 22} {Carry 28} {Dev 34} {Dev 32} {Tanisha 24} {Yashna 21}]

Example 2

// Golang program to demonstrate the
// example of sort.Stable() 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.Stable(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}]

Golang sort Package »




Comments and Discussions!

Load comments ↻





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