×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang sort.Ints() Function with Examples

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

sort.Ints()

The Ints() function is an inbuilt function of the sort package which is used to sort a given slice of Ints (int type of elements) in increasing order (ascending order).

It accepts a parameter (x []int) and returns nothing.

Syntax

func Ints(x []int)

Parameters

  • x : Slice of Ints to be sorted in ascending order.

Return Value

None.

Example 1

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

package main

import (
	"fmt"
	"sort"
)

func main() {
	x := []int{-123, 10, 20, 15, 0, -10}
	fmt.Println("x (Before):", x)
	sort.Ints(x)
	fmt.Println("x (After):", x)

	fmt.Println()

	x = []int{1, 2, 10, 0, 255, 65535, -65535}
	fmt.Println("x (Before):", x)
	sort.Ints(x)
	fmt.Println("x (After):", x)
}

Output:

x (Before): [-123 10 20 15 0 -10]
x (After): [-123 -10 0 10 15 20]

x (Before): [1 2 10 0 255 65535 -65535]
x (After): [-65535 0 1 2 10 255 65535]

Example 2

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

package main

import (
	"fmt"
	"sort"
)

func main() {
	x := []int{-123, 10, 20, 15, 0, -10}
	// Printing x, type, sorting status
	fmt.Println("x:", x)
	fmt.Printf("%T, %v\n", x, sort.IntsAreSorted(x))

	// Sorting x
	sort.Ints(x)

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

	fmt.Println()

	x = []int{-10, 0, 1, 2, 10, 255, 65535, 0}

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

	// Sorting x
	sort.Ints(x)

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

Output:

x: [-123 10 20 15 0 -10]
[]int, false
x: [-123 -10 0 10 15 20]
[]int, true

x: [-10 0 1 2 10 255 65535 0]
[]int, false
x: [-10 0 0 1 2 10 255 65535]
[]int, true

Golang sort Package »




Comments and Discussions!

Load comments ↻





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