SoFunction
Updated on 2025-03-05

Analysis of the method of sorting arrays of Golang algorithm problems by specified rules

package huawei
import (
    "fmt"
    "sort"
)
func Test09Base() {
    nums := [][]int{{1, 2, 3}, {2, 3, 4}, {2, 3, 1}, {1, 3, 1}}
firstIndex := 2 //Sort by second column
    result := arraySort(nums, firstIndex-1)
    (result)
}
//Sort nums according to the specified rules (Note: This firstIndex starts from 0)
func arraySort(nums [][]int, firstIndex int) [][]int {
//examine
    if len(nums) <= 1 {
        return nums
    }
    if firstIndex < 0 || firstIndex > len(nums[0])-1 {
        ("Warning: Param firstIndex should between 0 and len(nums)-1. The original array is returned.")
        return nums
    }
//Sorting
    mIntArray := &IntArray{nums, firstIndex}
    (mIntArray)
    return
}
type IntArray struct {
    mArr       [][]int
    firstIndex int
}
//IntArray implements interface
func (arr *IntArray) Len() int {
    return len()
}
func (arr *IntArray) Swap(i, j int) {
    [i], [j] = [j], [i]
}
func (arr *IntArray) Less(i, j int) bool {
    arr1 := [i]
    arr2 := [j]
    for index := ; index < len(arr1); index++ {
        if arr1[index] < arr2[index] {
            return true
        } else if arr1[index] > arr2[index] {
            return false
        }
    }
    return i < j
}