The array of Golang algorithm problems is analyzed according to the specified rule ordering method

  • 2020-06-07 04:37:36
  • OfStack

An example of Golang algorithm is presented in this paper. To share for your reference, specific as follows:

Given a 2-dimensional array, sort the 2-dimensional array by the i column (i starts at 1), and if the i column is the same, sort the same rows by the elements of the i+1 column,

If the elements in column i+1 are the same, then continue to compare column i+2, and so on, until the last column. If the i column is the same all the way to the last column, it is sorted in the original order.

Sample input:

1,2,3
2,3,4
2,3,1
1,3,1

Sorted by column 2, output:

1,2,3
2,3,1
1,3,1
2,3,4

Code implementation:

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

I hope that this article has been helpful in Go programming.


Related articles: