Algorithm Basics: Array-specific rule ordering problem (Golang implementation)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.