This article illustrates the way the Go language algorithm searches for the second largest element of the array. Share to everyone for your reference. Specifically as follows:
The principle of the algorithm is that when traversing an array, it always records the current largest element and the second largest element. The sample code is as follows:
Copy Code code as follows:
Package demo01
Import (
"FMT"
)
Func numbertestbase () {
Fmt. Println ("This is Numbertestbase")
Nums: = []int{12, 24, 2, 5, 13, 8, 7}
Fmt. Println ("Nums:", Nums)
Secondmax: = Getsecondmaxnum (Nums)
Fmt. Println ("secondmax=", Secondmax)
}
Func getsecondmaxnum (nums []int) int {
Length: = Len (nums)
If length = = 0 {
Panic ("Slice nums cannot be 0-size.")
}
If length = = 1 {
return Nums[0]
}
var max, Secondmax int
If nums[0] > nums[1] {
max = Nums[0]
Secondmax = nums[1]
} else {
max = Nums[1]
Secondmax = Nums[0]
}
For I: = 2; I < Len (nums); i++ {
If nums[i] > Secondmax {
If Nums[i] <= max {
Secondmax = Nums[i]
} else {
Secondmax, max = max, nums[i]
}
}
}
Return Secondmax
}
I hope this article will help you with your go language program.