This article describes the problem of Golang's positive integer specification rule sorting algorithm. Share it for your reference, as follows:
Given a string with many positive integers, you need to sort these positive integers and then return the positive integer at the specified position after sorting.
Sort requirements:Sort from small to large according to the integer composed of the last three digits of each positive integer
1) If there are less than three bits, compare them according to the integer composed of the actual number of bits.
2) If equal, sort in the original order in the input string
illustrate(Candidates do not need to check the following content, the caller guarantees):
1) The positive integers in the string are separated by a single space, and there are no spaces at the beginning and end of the string.
2) The format of positive integer is decimal, size: 1~1000000, the number of positive integers starts from non-zero
Example:
Like string content
1223 22 3232 2016
After sorting according to regulations
2016 22 1223 3232
The third number after query sorting is
1223
Code implementation:
import (
"errors"
"fmt"
"strconv"
"strings"
)
func Test6Base() {
s := "2115 22 2128 3115 4119 2016 2119"
findIndex := 2
result, err := findString(s, findIndex)
if err == nil {
("result:", result)
} else {
("Error:", ())
}
}
//Sort the resString according to the specified rules, and then return the string indexed to the findIndex position
func findString(resString string, findIndex int) (result int, err error) {
if resString == "" {
return -1, ("Param resString is an empty string.")
}
numsStr := (resString)
if findIndex < 0 || findIndex > len(numsStr)-1 {
return -1, ("Param findIndex is invalid.")
}
numsInt := convertToInt(numsStr)
//Bubblestone (stable)
var change bool = false
for i := 0; i < len(numsInt)-1; i++ {
change = false
for j := 1; j < len(numsInt)-i; j++ {
if numsInt[j]%1000 < numsInt[j-1]%1000 {
change = true
numsInt[j], numsInt[j-1] = numsInt[j-1], numsInt[j]
}
}
if !change {
break
}
}
(numsInt)
return numsInt[findIndex], nil
}
//Convert []string to []int
func convertToInt(numsStr []string) []int {
numsInt := make([]int, len(numsStr))
for i, v := range numsStr {
n, err := (v)
checkError(err, "string to integer")
numsInt[i] = n
}
return numsInt
}
I hope this article will be helpful to everyone's Go language programming.