English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This article illustrates the method of sorting an array according to a specified rule in Golang algorithm problems. Share it with everyone for reference, as follows:
Give a two-dimensional array, please sort this two-dimensional array by the i-th column (i from1Start sorting, if the i column is the same, then sort the same rows by the i+1column elements are sorted,
If the i+1column elements are also the same, then continue to compare the i+2column, and so on, until the last column. If the elements of the i-th column to the last column are the same, then sort in the original order.
Sample input:
1,2,3
2,3,4
2,3,1
1,3,1
Sort by the2Column sorting, 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 //Sort by the second column result := arraySort(nums, firstIndex-1) fmt.Println(result) } //Sort nums according to the specified rules (note: this firstIndex starts from 0) 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 } //Sort mIntArray := &IntArray{nums, firstIndex} sort.Sort(mIntArray) return mIntArray.mArr } type IntArray struct { mArr [][]int firstIndex int } //IntArray implements the 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 }1[index] > arr2[index] { return false } } return i < j }
I hope this article will be helpful to everyone in programming with the Go language.
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please report any violations by email to codebox.com (replace # with @ when sending an email), and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.