How to obtain the index permutation after the sorting

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

    I think we can solve this problem without using vector. I'm newbie, to be honest, i don't understand what you wrote above, and all of you used vector which i will study later :))) ( i'm lazy) Here's my way :

    // First, copy array a[] to array b[]

       void copyarray(double b[],double a[],int n){
         for(int i=0;i<n;i++)b[i]=a[i];
        }
    

    // Second, sort array a[] ( decrease )

    /*Third, " sorter " array a[], that means: in array a[],if there exists same values, they will merge into one ! i will set array o[] is "the sorted array a[] " */

     void sorter(double o[],double a[],int n,int &dem){   
         int i;
         o[0]=a[0];
         for(i=1;i<n;i++){
            if(a[i]!=a[i-1]){
              dem++; o[dem]=a[i];
             }
          }
          dem++;
     }
    

    /* 4th, our main goal: get the index: i will put the index into array c[] */

    void index_sort(double o[],double b[], double c[], int dem, int n){
        int i,j,chiso=0;
        for(j=0;j<dem;j++){
           for(i=0;i<n;i++){
              if(b[i]==o[j]){
                 c[chiso]=i;
                 chiso++;
               }
            }
         }
     }
    
      // DONE!
     int main(){
            int n,dem=0;
             double a[100],b[100],c[100],o[100];
             cin>>n;
             input(a,n);
             copyarray(b,a,n);
             copyarray(c,a,n);
             sort(a,n);
             sorter(o,a,n,dem); 
             index_sort(o,b,c,dem,n); 
             for(int i=0;i<n;i++) cout<<c[i]<<" ";
       }
    
    0 讨论(0)
提交回复
热议问题