简体   繁体   中英

How to sort second array and arrange first array with respect to sorted second array in less than O(n^2) time?

I have sorted the second array and arrange first array with respect to sorted second array in O(n^2) time and my code is something like this-

//c++ code
void sort(int size,int arr1[],int arr2[])
{
    for(int i=0;i<size-1;++i)
    {
        for(int j=i+1;j<size;++j)
        {
            if(arr2[i]>arr2[j])
            {
                swap(arr2[i],arr2[j]);
                swap(arr1[i],arr1[j]);
            }
            //for duplicate data in arr2 
            if(arr2[i]==arr2[j])
            {
                if(arr1[i]>arr1[j])
                {                                   
                    swap(arr1[i],arr1[j]);
                }
            }
        }
    }
}

for example if-

arr1=[2,1,3,9,7,12,5,13]
arr2=[1,3,6,9,2,3,1,3]

after sorting arr2 with respect to arr1

arr1=[2,5,7,1,12,13,3,9]
arr2=[1,1,2,3,3,3,6,9]

the time complexity of this function is O(n^2) now what will be the better approach to sort it?

As indicated by this answer , build an index and sort on the index.

Then you can use the index array to repopulate the arrays. Then you can also use std::sort which is O(n log n) instead of the O(n^2) approach you were using:

#include <algorithm>
#include <iostream>
#include <numeric>

int main()
{
    int arr1 [] = {2,1,3,9,7,12,5,13};
    int arr2 [] = {1,3,6,9,2,3,1,3};
    int index[8];
    std::iota(index, index + 8, 0);
    std::sort(std::begin(index), std::end(index), [&](int n1, int n2) { return arr2[n1] < arr2[n2]; });
    for (auto i : index)
      std::cout << arr1[i] << " ";
    std::cout << "\n";
    for (auto i : index)
      std::cout << arr2[i] << " ";
}

Output:

2 5 7 1 12 13 3 9 
1 1 2 3 3 3 6 9 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM