Go Slice - Program to Find Largest & Smallest Element

Example 1: Finding the largest element in a Slice

// Go program to find largest number in a Slice
package main

import "fmt"

// Main function
func main() {

// Let’s define an slice first
arr := []int{2, 11, 22, 5, 6, 3, 1, 9}
fmt.Println("Largest Number:", LargestNumber(arr))

//Another Example
anotherarr := []int{144, 666, 99, 677, 433, 422, 255}
fmt.Println("Largest Number:", LargestNumber(anotherarr))
}

func LargestNumber(arr []int) int {
var temp int
for i := 0; i < len(arr); i++ {
for j := i + 1; j < len(arr); j++ {
if arr[i] > arr[j] {
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
}
return arr[len(arr)-1]
}

Output:




Example 2: Finding the smallest element in a Slice

// Go program to find smallest number in a Slice
package main

import "fmt"

// Main function
func main() {

// Let’s define a slice first
arr := []int{2, 11, 22, 5, 6, 3, 1, 9}
fmt.Println("Smallest Number:", SmallestNumber(arr))

//Another Example
anotherarr := []int{144, 666, 99, 677, 433, 422, 22}
fmt.Println("Smallest Number:", SmallestNumber(anotherarr))
}

func SmallestNumber(arr []int) int {
var temp int
for i := 0; i < len(arr); i++ {
for j := i + 1; j < len(arr); j++ {
if arr[i] > arr[j] {
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
}
return arr[0]
}

Output:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete