Go language algorithm for finding the second largest element of an array

  • 2020-05-17 05:40:26
  • OfStack

In this paper, an example of the Go language algorithm is presented to find the second element of an array. Share with you for your reference. The details are as follows:

The principle of this algorithm is that when traversing groups, the current largest element and the second largest element are always recorded. The sample code is 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 has been helpful to your programming of Go language.


Related articles: