How to obtain the index permutation after the sorting

前端 未结 7 1454
野性不改
野性不改 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:17

    Well in c++ we can use pair datatype to do this easily. Sample code below;

    arr = {5, 16, 4, 7};
    vector >V;
    for(int i=0;i<4;i++){
        pairP=make_pair(arr[i],i);
        V.push_back(P);
    }
    
    sort(V.begin(),V.end());
    

    So V[i].first is the ith value and V[i].second is the ith index. So to print the index in the sorted array.

    for(int i=0;i<4;i++)cout<

    Note that while sorting an array (or vector) of pair items, array is first sorted based on the first values. If two pair have same first value then they are sorted based on their second value.

提交回复
热议问题