Map by key and sort by value

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Look at a question:
Find and sort
Title: Enter any (user, score) sequence, can get grades from high to low or from low to high arrangement, the same score
The rules are processed before the first entries are sorted.
Examples are as follows:
Jack 70
Peter 96
Tom 70
Smith 67
From high to low score
Peter 96
Jack 70
Tom 70
Smith 67
From low to high
Smith 67
Tom 70
Jack 70
Peter 96

1. Sort by value
2. Can increment sort and descending sort
3, ensure the stability of the sequencing

Golang map sorted by key

//golang的map不保证有序性,所以按key排序需要取出key,对key排序,再遍历输出valuepackage mainimport (    "fmt"    "sort")func main() {    // To create a map as input    m := make(map[int]string)    m[1] = "a"    m[2] = "c"    m[0] = "b"    // To store the keys in slice in sorted order    var keys []int    for k := range m {        keys = append(keys, k)    }    sort.Ints(keys)    // To perform the opertion you want    for _, k := range keys {        fmt.Println("Key:", k, "Value:", m[k])    }}

Golang map sorted by value

//要对golang map按照value进行排序,思路是直接不用map,用struct存放key和value,实现sort接口,就可以调用sort.Sort进行排序了。// A data structure to hold a key/value pair.type Pair struct {    Key   string    Value int}// A slice of Pairs that implements sort.Interface to sort by Value.type PairList []Pairfunc (p PairList) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }func (p PairList) Len() int           { return len(p) }func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }// A function to turn a map into a PairList, then sort and return it.func sortMapByValue(m map[string]int) PairList {    p := make(PairList, len(m))    i := 0    for k, v := range m {        p[i] = Pair{k, v}    }    sort.Sort(p)    return p}

Golang Map Increment Sort

//sort.Sort是递增排序,如果要实现递减排序,用sort.Reversepackage mainimport (    "fmt"    "sort")func main() {    a := []int{4,3,2,1,5,9,8,7,6}    sort.Sort(sort.Reverse(sort.IntSlice(a)))    fmt.Println("After reversed: ", a)}

Golang Stability of Map sequencing

//sort不保证排序的稳定性(两个相同的值,排序之后相对位置不变),排序的稳定性由sort.Stable来保证。package mainimport (    "fmt"    "sort")type person struct {  Name string  Age int}type personSlice []personfunc (s personSlice) Len() int { return len(s) }func (s personSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }func (s personSlice) Less(i, j int) bool { return s[i].Age < s[j].Age }func main() {    a := personSlice {      {        Name: "AAA",        Age: 55,      },      {        Name: "BBB",        Age: 22,      },      {        Name: "CCC",        Age: 0,      },      {        Name: "DDD",        Age: 22,      },      {        Name: "EEE",        Age: 11,      },      }    sort.Stable(a)    fmt.Println(a)}

C + + stability of sort, increment and decrement, sort by value

Take a look at the subject of C + + solution, C + + sort of the third parameter to define the sorting method, that is, by key or value sort, increment or decrement sort, etc., stable_sort to ensure the stability of the order, the main ideas and Golang solution similar, Use structs to encapsulate key and value instead of map. #include <iostream> #include <vector> #include <algorithm> #include <string>using namespace std    ; struct student{string name; int score;}; BOOL Cmp0 (const student &a, const student &b) {//from high to low sort return a.score > B.score;} BOOL Cmp1 (const student &a, const student &b) {//from low to high sort return A.score < B.score;}    int main () {//freopen ("In.txt", "R", stdin);    Freopen ("OUT.txt", "w", stdout);    int N, type;                 while (CIN >> n >> type) {vector<student> stud (n);        for (int i = 0; i < N; i + +) {cin >> stud[i].name >> Stud[i].score;   } if (type = = 0) stable_sort (Stud.begin (), Stud.end (), cmp0);                 Stable sort Else stable_sort (Stud.begin (), Stud.end (), CMP1);            for (int i = 0; i < N; i + +) {cout << stud[i].name << "<< stud[i].score << Endl; }} return 0;}
Related Article

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.