An example of Golang positive integer specified rule sort algorithm is presented in this paper. I will share it with you for your reference as follows:
There are many positive integers in a given string, so you need to sort them, and then return the positive integer at the specified position after sorting
Sorting requirements: according to the last three digits of each positive integer integer from small to large sorting
- if there are less than 3 digits, the comparison shall be made according to the integer composed of actual digits
- if equal, sort in the original order of the input string
Description (no need for examinee to check the following content, the caller guarantees) :
- 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
- the format of the positive integer is in base 10, size: 1~1000000, and the positive integer digits start from non-zero
Example:
Like string content
1223 22 3232 2016
After sorting by the rules
2016 22 1223 3232
The third number of queries sorted is
1223
Code implementation:
package huawei
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 {
fmt.Println("result:", result)
} else {
fmt.Println("Error:", err.Error())
}
}
// will resString Sort by the specified rule, and then return the index as findIndex String of positions
func findString(resString string, findIndex int) (result int, err error) {
if resString == "" {
return -1, errors.New("Param resString is an empty string.")
}
numsStr := strings.Fields(resString)
if findIndex < 0 || findIndex > len(numsStr)-1 {
return -1, errors.New("Param findIndex is invalid.")
}
numsInt := convertToInt(numsStr)
// Bubble sort ( 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
}
}
fmt.Println(numsInt)
return numsInt[findIndex], nil
}
// will []string to []int
func convertToInt(numsStr []string) []int {
numsInt := make([]int, len(numsStr))
for i, v := range numsStr {
n, err := strconv.Atoi(v)
checkError(err, "string to integer")
numsInt[i] = n
}
return numsInt
}
I hope this article has been helpful to you in the programming of Go language.