Given a two-dimensional array, sort the two-dimensional array by column I (I starts with 1), and if column I is the same, sort the same rows by the elements of column i+1.
If the elements of column i+1 are also the same, continue to compare column i+2, and so on, until the last column. If column I is the same as the last column, it is sorted in the original order.
Sample input:
The
2,3,4
2,3,1
1,3,1
Sort by 2nd column, output:
The
2,3,1
1,3,1
2,3,4
Code implementation:
PackageHuaweiImport("FMT" "Sort")funcTest09base () {nums: = []int{{1,2,3},{2,3,4},{2,3,1},{1,3,1}} FirstIndex: =2 //Sort by second columnResult: = ArraySort (Nums, FirstIndex-1) FMT. PRINTLN (Result)}//Sort the nums by the specified rules (note: This firstindex starts from 0)funcArraySort (Nums []int, FirstIndexint) [][]int{//Check if Len(nums) <=1{returnNums}ifFirstIndex <0|| FirstIndex >Len(Nums[0])-1{FMT. Println ("Warning:param FirstIndex should between 0 and Len (nums)-1. The original array is returned. ")returnNums}//SortMintarray: = &intarray{nums, firstindex} sort. Sort (Mintarray)returnMintarray.marr}typeIntarraystruct{MARR []intFirstIndexint}//intarray implementing the Sort.interface interfacefunc(arr *intarray) Len ()int{return Len(Arr.marr)}func(arr *intarray) Swap (I, Jint) {Arr.marr[i], arr.marr[j] = Arr.marr[j], Arr.marr[i]}func(arr *intarray) Less (I, Jint)BOOL{arr1: = arr.marr[i] arr2: = Arr.marr[j] forIndex: = Arr.firstindex; Index <Len(ARR1); index++ {ifArr1[index] < Arr2[index] {return true}Else ifArr1[index] > Arr2[index] {return false} }returnI < J}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm Basics: Array-specific rule ordering problem (Golang implementation)