How to obtain the index permutation after the sorting

前端 未结 7 1443
野性不改
野性不改 2020-12-13 06:24

Given an array arr = {5, 16, 4, 7}, we can sort it through sort(arr, arr+sizeof(arr)/sizeof(arr[0])). so now the array arr = {4, 5, 7, 16}

7条回答
  •  既然无缘
    2020-12-13 07:10

    Create an array of indexes, fill it with numbers 0..N-1, and sort it using a custom comparator. The comparator should compare items from the original array at indexes lhs and rhs. Sorting the array of indexes this way reorders them as a permutation:

    vector data = {5, 16, 4, 7};   
    vector index(data.size(), 0);
    for (int i = 0 ; i != index.size() ; i++) {
        index[i] = i;
    }
    sort(index.begin(), index.end(),
        [&](const int& a, const int& b) {
            return (data[a] < data[b]);
        }
    );
    for (int i = 0 ; i != index.size() ; i++) {
        cout << index[i] << endl;
    }
    

    This prints 2, 0, 3, 1

    Here is a demo on ideone.

    Note: you can use index to retrieve the data in sorted order:

    for (int i = 0 ; i != index.size() ; i++) {
        cout << data[index[i]] << endl;
    }
    

提交回复
热议问题