📌  相关文章
📜  根据给定的索引对数组重新排序

📅  最后修改于: 2022-05-13 01:57:47.511000             🧑  作者: Mango

根据给定的索引对数组重新排序

给定两个相同大小的整数数组“arr[]”和“index[]”,根据给定的索引数组对“arr[]”中的元素重新排序。不允许给定数组 arr 的长度。

例子:

Input:  arr[]   = [10, 11, 12];
        index[] = [1, 0, 2];
Output: arr[]   = [11, 10, 12]
        index[] = [0,  1,  2] 

Input:  arr[]   = [50, 40, 70, 60, 90]
        index[] = [3,  0,  4,  1,  2]
Output: arr[]   = [40, 60, 90, 50, 70]
        index[] = [0,  1,  2,  3,   4]

预期时间复杂度 O(n) 和辅助空间 O(1)

我们强烈建议您最小化您的浏览器并首先自己尝试。
一个简单的解决方案是使用与给定数组大小相同的辅助数组 temp[]。遍历给定的数组并使用 index[] 将所有元素放在 temp[] 中的正确位置。最后将 temp[] 复制到 arr[] 并将 index[i] 的所有值设置为 i。

C++
// C++ program to sort an array according to given
// indexes
#include
 
using namespace std;
 
// Function to reorder elements of arr[] according
// to index[]
void reorder(int arr[], int index[], int n)
{
    int temp[n];
 
    // arr[i] should be present at index[i] index
    for (int i=0; i


Java
//Java to find positions of zeroes flipping which
// produces maximum number of consecutive 1's
 
import java.util.Arrays;
 
class Test
{
    static int arr[] = new int[]{50, 40, 70, 60, 90};
    static int index[] = new int[]{3,  0,  4,  1,  2};
     
    // Method to reorder elements of arr[] according
    // to index[]
    static void reorder()
    {
        int temp[] = new int[arr.length];
      
        // arr[i] should be present at index[i] index
        for (int i=0; i


Python3
# Python3 program to sort
# an array according to given
# indexes
 
# Function to reorder
# elements of arr[] according
# to index[]
def reorder(arr,index, n):
 
    temp = [0] * n;
 
    # arr[i] should be
        # present at index[i] index
    for i in range(0,n):
        temp[index[i]] = arr[i]
 
    # Copy temp[] to arr[]
    for i in range(0,n):
        arr[i] = temp[i]
        index[i] = i
     
# Driver program
arr = [50, 40, 70, 60, 90]
index = [3, 0, 4, 1, 2]
n = len(arr)
 
reorder(arr, index, n)
 
print("Reordered array is:")
for i in range(0,n):
    print(arr[i],end = " ")
 
print("\nModified Index array is:")
for i in range(0,n):
    print(index[i],end = " ")
 
# This code is contributed by
# Smitha Dinesh Semwal


C#
// C# to find positions of zeroes flipping which
// produces maximum number of consecutive 1's
using System;
  
public class Test{
     
    static int []arr = new int[]{50, 40, 70, 60, 90};
    static int []index = new int[]{3,  0,  4,  1,  2};
      
    // Method to reorder elements of arr[] according
    // to index[]
    static void reorder()
    {
        int []temp = new int[arr.Length];
       
        // arr[i] should be present at index[i] index
        for (int i=0; i


PHP


Javascript


C++
// A O(n) time and O(1) extra space C++ program to
// sort an array according to given indexes
#include
 
using namespace std;
 
// Function to reorder elements of arr[] according
// to index[]
void reorder(int arr[], int index[], int n)
{
    // Fix all elements one by one
    for (int i=0; i


Java
//A O(n) time and O(1) extra space Java program to
//sort an array according to given indexes
 
import java.util.Arrays;
 
class Test
{
    static int arr[] = new int[]{50, 40, 70, 60, 90};
    static int index[] = new int[]{3,  0,  4,  1,  2};
     
    // Method to reorder elements of arr[] according
    // to index[]
    static void reorder()
    {
        // Fix all elements one by one
        for (int i=0; i


Python3
# A O(n) time and O(1) extra space Python3 program to
# sort an array according to given indexes
 
# Function to reorder elements of arr[] according
# to index[]
def reorder(arr, index, n):
 
    # Fix all elements one by one
    for i in range(0,n):
 
           #  While index[i] and arr[i] are not fixed
           while (index[i] != i):
         
               # Store values of the target (or correct)
               # position before placing arr[i] there
               oldTargetI = index[index[i]]
               oldTargetE = arr[index[i]]
 
               # Place arr[i] at its target (or correct)
               # position. Also copy corrected index for
               # new position
               arr[index[i]] = arr[i]
               index[index[i]] = index[i]
 
               # Copy old target values to arr[i] and
               # index[i]
               index[i] = oldTargetI
               arr[i] = oldTargetE
 
 
# Driver program
arr = [50, 40, 70, 60, 90]
index= [3, 0, 4, 1, 2]
n = len(arr)
 
reorder(arr, index, n)
 
print("Reordered array is:")
for  i in range(0, n):
    print(arr[i],end=" ")
 
print("\nModified Index array is:")
for i in range(0, n):
    print(index[i] ,end=" ")
 
# This code is contributed by
# Smitha Dinesh Semwal


C#
//A O(n) time and O(1) extra space C# program to
//sort an array according to given indexes
using System;
 
public class Test
{
    static int []arr = new int[]{50, 40, 70, 60, 90};
    static int []index = new int[]{3,  0,  4,  1,  2};
      
    // Method to reorder elements of arr[] according
    // to index[]
    static void reorder()
    {
        // Fix all elements one by one
        for (int i=0; i


Javascript


C++
//C++ code to reorder an array according to given indices
#include 
 
using namespace std;
 
int heapSize;
 
void swap ( int &a, int &b ) {
    int temp = a;
    a = b;
    b = temp;
}
 
void heapify( int arr[], int index[], int i )
{
    int largest = i;
    // left child in 0 based indexing
    int left = 2 * i + 1;
    // right child in 1 based indexing
    int right = 2 * i + 2;
    // find largest index from root, left and right child
    if( left < heapSize && index[left] > index[largest] )
    {
        largest = left;
    }
    if( right < heapSize && index[right] > index[largest] )
    {
        largest = right;
    }
     
    if ( largest != i ) {
        //swap arr whenever index is swapped
        swap(arr[largest], arr[i]);
        swap(index[largest], index[i]);
        heapify(arr, index, largest);
    }
}
 
void heapSort( int arr[], int index[], int n ) {
// Build heap
    for ( int i = ( n - 1 ) / 2 ; i >= 0 ; i-- ) {
        heapify(arr, index, i);
    }
    // Swap the largest element of index(first element)
    // with the last element
    for ( int i = n - 1 ; i > 0 ; i-- ) {
        swap(index[0], index[i]);
        //swap arr whenever index is swapped
        swap(arr[0], arr[i]);
        heapSize--;
        heapify(arr, index, 0);
    }
}
 
// Driver Code
int main() {
    int arr[] = {50, 40, 70, 60, 90};
    int index[] = {3,  0,  4,  1,  2};
    int n = sizeof(arr)/sizeof(arr[0]);
    heapSize = n;
    heapSort(arr, index, n);
 
    cout << "Reordered array is: \n";
    for ( int i = 0 ; i < n ; i++ )
        cout << arr[i] << " ";
         
        cout << "\nModified Index array is: \n";
    for (int i=0; i


Java
// Java code to reorder an array
// according to given indices
class GFG{
     
static int heapSize;
 
public static void heapify(int arr[],
                           int index[], int i)
{
    int largest = i;
     
    // left child in 0 based indexing
    int left = 2 * i + 1;
     
    // right child in 1 based indexing
    int right = 2 * i + 2;
     
    // Find largest index from root,
    // left and right child
    if (left < heapSize &&
        index[left] > index[largest] )
    {
        largest = left;
    }
    if (right < heapSize &&
        index[right] > index[largest] )
    {
        largest = right;
    }
      
    if (largest != i)
    {
         
        // swap arr whenever index is swapped
        int temp = arr[largest];
        arr[largest] = arr[i];
        arr[i] = temp;
         
        temp = index[largest];
        index[largest] = index[i];
        index[i] = temp;
         
        heapify(arr, index, largest);
    }
}
  
public static void heapSort(int arr[],
                            int index[], int n)
{
     
    // Build heap
    for(int i = (n - 1) / 2 ; i >= 0 ; i--)
    {
        heapify(arr, index, i);
    }
     
    // Swap the largest element of
    // index(first element)
    // with the last element
    for(int i = n - 1 ; i > 0 ; i--)
    {
        int temp = index[0];
        index[0] = index[i];
        index[i] = temp;
         
        // swap arr whenever index is swapped
        temp = arr[0];
        arr[0] = arr[i];
        arr[i] = temp;
         
        heapSize--;
        heapify(arr, index, 0);
    }
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 50, 40, 70, 60, 90 };
    int index[] = { 3, 0, 4, 1, 2 };
    int n = arr.length;
     
    heapSize = n;
    heapSort(arr, index, n);
     
    System.out.println("Reordered array is: ");
    for(int i = 0 ; i < n ; i++)
        System.out.print(arr[i] + " ");
         
    System.out.println();  
     
    System.out.println("Modified Index array is: ");
    for(int i = 0; i < n; i++)
        System.out.print(index[i] + " ");
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 code to reorder an array
# according to given indices
def heapify(arr, index, i):
     
    largest = i
     
    # left child in 0 based indexing
    left = 2 * i + 1
     
    # right child in 1 based indexing
    right = 2 * i + 2
     
    global heapSize
 
    # Find largest index from root,
    # left and right child
    if (left < heapSize and
        index[left] > index[largest]):
        largest = left
 
    if (right < heapSize and
        index[right] > index[largest]):
        largest = right
 
    if (largest != i):
         
        # Swap arr whenever index is swapped
        arr[largest], arr[i] = arr[i], arr[largest]
        index[largest], index[i] = index[i], index[largest]
 
        heapify(arr, index, largest)
 
def heapSort(arr, index, n):
     
    # Build heap
    global heapSize
     
    for i in range(int((n - 1) / 2), -1, -1):
        heapify(arr, index, i)
         
    # Swap the largest element of
    # index(first element) with
    # the last element
    for i in range(n - 1, 0, -1):
        index[0], index[i] = index[i], index[0]
         
        # Swap arr whenever index is swapped
        arr[0], arr[i] = arr[i], arr[0]
 
        heapSize -= 1
        heapify(arr, index, 0)
 
# Driver Code
arr = [ 50, 40, 70, 60, 90 ]
index = [ 3, 0, 4, 1, 2 ]
 
n = len(arr)
global heapSize
heapSize = n
heapSort(arr, index, n)
 
print("Reordered array is: ")
print(*arr, sep = ' ')
print("Modified Index array is: ")
print(*index, sep = ' ')
 
# This code is contributed by avanitrachhadiya2155


C#
// C# code to reorder an array
// according to given indices
using System;
using System.Collections.Generic;
 
class GFG{
     
static int heapSize;
 
public static void heapify(int[] arr,
                           int[] index,
                           int i)
{
    int largest = i;
     
    // left child in 0 based indexing
    int left = 2 * i + 1;
      
    // right child in 1 based indexing
    int right = 2 * i + 2;
      
    // Find largest index from root,
    // left and right child
    if (left < heapSize &&
        index[left] > index[largest] )
    {
        largest = left;
    }
    if (right < heapSize &&
        index[right] > index[largest] )
    {
        largest = right;
    }
       
    if (largest != i)
    {
         
        // Swap arr whenever index is swapped
        int temp = arr[largest];
        arr[largest] = arr[i];
        arr[i] = temp;
          
        temp = index[largest];
        index[largest] = index[i];
        index[i] = temp;
          
        heapify(arr, index, largest);
    }
}
   
public static void heapSort(int[] arr,
                            int[] index,
                            int n)
{
     
    // Build heap
    for(int i = (n - 1) / 2 ; i >= 0 ; i--)
    {
        heapify(arr, index, i);
    }
      
    // Swap the largest element of
    // index(first element)
    // with the last element
    for(int i = n - 1 ; i > 0 ; i--)
    {
        int temp = index[0];
        index[0] = index[i];
        index[i] = temp;
          
        // Swap arr whenever index
        // is swapped
        temp = arr[0];
        arr[0] = arr[i];
        arr[i] = temp;
          
        heapSize--;
        heapify(arr, index, 0);
    }
}
 
// Driver Code
static void Main()
{
    int[] arr = { 50, 40, 70, 60, 90 };
    int[] index = { 3, 0, 4, 1, 2 };
    int n = arr.Length;
      
    heapSize = n;
    heapSort(arr, index, n);
      
    Console.WriteLine("Reordered array is: ");
    for(int i = 0 ; i < n ; i++)
        Console.Write(arr[i] + " ");
          
    Console.WriteLine();
      
    Console.WriteLine("Modified Index array is: ");
    for(int i = 0; i < n; i++)
        Console.Write(index[i] + " ");
}
}
 
// This code is contributed by divyesh072019


Javascript


C++
// A O(n) time and O(1) extra space C++ program to
// sort an array according to given indexes
#include 
 
using namespace std;
 
// Function to reorder elements of arr[] according
// to index[]
void reorder(int arr[], int index_arr[], int n)
{
    // Fix all elements one by one
    for (int i = 0; i < n; i++) {
        // While index[i] and arr[i] are not fixed
        while (index_arr[i] != i) {
            swap(arr[i], arr[index_arr[i]]);
            swap(index_arr[i], index_arr[index_arr[i]]);
        }
    }
}
 
// Driver program
int main()
{
    int arr[] = { 50, 40, 70, 60, 90 };
    int index[] = { 3, 0, 4, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    reorder(arr, index, n);
 
    cout << "Reordered array is: \n";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
 
    cout << "\nModified Index array is: \n";
    for (int i = 0; i < n; i++)
        cout << index[i] << " ";
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


输出:

Reordered array is: 
40 60 90 50 70 
Modified Index array is: 
0 1 2 3 4

感谢gccode提出上述解决方案。

我们可以在没有辅助数组的情况下解决它。下面是算法。

1) Do following for every element arr[i]
   a) While index[i] is not equal to i
       (i)  Store array and index values of the target (or 
            correct) position where arr[i] should be placed.
            The correct position for arr[i] is index[i]
       (ii) Place arr[i] at its correct position. Also
            update index value of correct position.
       (iii) Copy old values of correct position (Stored in
            step (i)) to arr[i] and index[i] as the while 
            loop continues for i.

下面是上述算法的实现。

C++

// A O(n) time and O(1) extra space C++ program to
// sort an array according to given indexes
#include
 
using namespace std;
 
// Function to reorder elements of arr[] according
// to index[]
void reorder(int arr[], int index[], int n)
{
    // Fix all elements one by one
    for (int i=0; i

Java

//A O(n) time and O(1) extra space Java program to
//sort an array according to given indexes
 
import java.util.Arrays;
 
class Test
{
    static int arr[] = new int[]{50, 40, 70, 60, 90};
    static int index[] = new int[]{3,  0,  4,  1,  2};
     
    // Method to reorder elements of arr[] according
    // to index[]
    static void reorder()
    {
        // Fix all elements one by one
        for (int i=0; i

Python3

# A O(n) time and O(1) extra space Python3 program to
# sort an array according to given indexes
 
# Function to reorder elements of arr[] according
# to index[]
def reorder(arr, index, n):
 
    # Fix all elements one by one
    for i in range(0,n):
 
           #  While index[i] and arr[i] are not fixed
           while (index[i] != i):
         
               # Store values of the target (or correct)
               # position before placing arr[i] there
               oldTargetI = index[index[i]]
               oldTargetE = arr[index[i]]
 
               # Place arr[i] at its target (or correct)
               # position. Also copy corrected index for
               # new position
               arr[index[i]] = arr[i]
               index[index[i]] = index[i]
 
               # Copy old target values to arr[i] and
               # index[i]
               index[i] = oldTargetI
               arr[i] = oldTargetE
 
 
# Driver program
arr = [50, 40, 70, 60, 90]
index= [3, 0, 4, 1, 2]
n = len(arr)
 
reorder(arr, index, n)
 
print("Reordered array is:")
for  i in range(0, n):
    print(arr[i],end=" ")
 
print("\nModified Index array is:")
for i in range(0, n):
    print(index[i] ,end=" ")
 
# This code is contributed by
# Smitha Dinesh Semwal

C#

//A O(n) time and O(1) extra space C# program to
//sort an array according to given indexes
using System;
 
public class Test
{
    static int []arr = new int[]{50, 40, 70, 60, 90};
    static int []index = new int[]{3,  0,  4,  1,  2};
      
    // Method to reorder elements of arr[] according
    // to index[]
    static void reorder()
    {
        // Fix all elements one by one
        for (int i=0; i

Javascript


输出:

Reordered array is: 
40 60 90 50 70 
Modified Index array is: 
0 1 2 3 4

感谢 shyamala_lokre 提出上述解决方案。

另一种不使用辅助数组的方法是对数组进行排序。
对索引数组进行排序并自定义排序以在交换 index[] 数据时交换 arr[] 数据。

C++

//C++ code to reorder an array according to given indices
#include 
 
using namespace std;
 
int heapSize;
 
void swap ( int &a, int &b ) {
    int temp = a;
    a = b;
    b = temp;
}
 
void heapify( int arr[], int index[], int i )
{
    int largest = i;
    // left child in 0 based indexing
    int left = 2 * i + 1;
    // right child in 1 based indexing
    int right = 2 * i + 2;
    // find largest index from root, left and right child
    if( left < heapSize && index[left] > index[largest] )
    {
        largest = left;
    }
    if( right < heapSize && index[right] > index[largest] )
    {
        largest = right;
    }
     
    if ( largest != i ) {
        //swap arr whenever index is swapped
        swap(arr[largest], arr[i]);
        swap(index[largest], index[i]);
        heapify(arr, index, largest);
    }
}
 
void heapSort( int arr[], int index[], int n ) {
// Build heap
    for ( int i = ( n - 1 ) / 2 ; i >= 0 ; i-- ) {
        heapify(arr, index, i);
    }
    // Swap the largest element of index(first element)
    // with the last element
    for ( int i = n - 1 ; i > 0 ; i-- ) {
        swap(index[0], index[i]);
        //swap arr whenever index is swapped
        swap(arr[0], arr[i]);
        heapSize--;
        heapify(arr, index, 0);
    }
}
 
// Driver Code
int main() {
    int arr[] = {50, 40, 70, 60, 90};
    int index[] = {3,  0,  4,  1,  2};
    int n = sizeof(arr)/sizeof(arr[0]);
    heapSize = n;
    heapSort(arr, index, n);
 
    cout << "Reordered array is: \n";
    for ( int i = 0 ; i < n ; i++ )
        cout << arr[i] << " ";
         
        cout << "\nModified Index array is: \n";
    for (int i=0; i

Java

// Java code to reorder an array
// according to given indices
class GFG{
     
static int heapSize;
 
public static void heapify(int arr[],
                           int index[], int i)
{
    int largest = i;
     
    // left child in 0 based indexing
    int left = 2 * i + 1;
     
    // right child in 1 based indexing
    int right = 2 * i + 2;
     
    // Find largest index from root,
    // left and right child
    if (left < heapSize &&
        index[left] > index[largest] )
    {
        largest = left;
    }
    if (right < heapSize &&
        index[right] > index[largest] )
    {
        largest = right;
    }
      
    if (largest != i)
    {
         
        // swap arr whenever index is swapped
        int temp = arr[largest];
        arr[largest] = arr[i];
        arr[i] = temp;
         
        temp = index[largest];
        index[largest] = index[i];
        index[i] = temp;
         
        heapify(arr, index, largest);
    }
}
  
public static void heapSort(int arr[],
                            int index[], int n)
{
     
    // Build heap
    for(int i = (n - 1) / 2 ; i >= 0 ; i--)
    {
        heapify(arr, index, i);
    }
     
    // Swap the largest element of
    // index(first element)
    // with the last element
    for(int i = n - 1 ; i > 0 ; i--)
    {
        int temp = index[0];
        index[0] = index[i];
        index[i] = temp;
         
        // swap arr whenever index is swapped
        temp = arr[0];
        arr[0] = arr[i];
        arr[i] = temp;
         
        heapSize--;
        heapify(arr, index, 0);
    }
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 50, 40, 70, 60, 90 };
    int index[] = { 3, 0, 4, 1, 2 };
    int n = arr.length;
     
    heapSize = n;
    heapSort(arr, index, n);
     
    System.out.println("Reordered array is: ");
    for(int i = 0 ; i < n ; i++)
        System.out.print(arr[i] + " ");
         
    System.out.println();  
     
    System.out.println("Modified Index array is: ");
    for(int i = 0; i < n; i++)
        System.out.print(index[i] + " ");
}
}
 
// This code is contributed by divyeshrabadiya07

Python3

# Python3 code to reorder an array
# according to given indices
def heapify(arr, index, i):
     
    largest = i
     
    # left child in 0 based indexing
    left = 2 * i + 1
     
    # right child in 1 based indexing
    right = 2 * i + 2
     
    global heapSize
 
    # Find largest index from root,
    # left and right child
    if (left < heapSize and
        index[left] > index[largest]):
        largest = left
 
    if (right < heapSize and
        index[right] > index[largest]):
        largest = right
 
    if (largest != i):
         
        # Swap arr whenever index is swapped
        arr[largest], arr[i] = arr[i], arr[largest]
        index[largest], index[i] = index[i], index[largest]
 
        heapify(arr, index, largest)
 
def heapSort(arr, index, n):
     
    # Build heap
    global heapSize
     
    for i in range(int((n - 1) / 2), -1, -1):
        heapify(arr, index, i)
         
    # Swap the largest element of
    # index(first element) with
    # the last element
    for i in range(n - 1, 0, -1):
        index[0], index[i] = index[i], index[0]
         
        # Swap arr whenever index is swapped
        arr[0], arr[i] = arr[i], arr[0]
 
        heapSize -= 1
        heapify(arr, index, 0)
 
# Driver Code
arr = [ 50, 40, 70, 60, 90 ]
index = [ 3, 0, 4, 1, 2 ]
 
n = len(arr)
global heapSize
heapSize = n
heapSort(arr, index, n)
 
print("Reordered array is: ")
print(*arr, sep = ' ')
print("Modified Index array is: ")
print(*index, sep = ' ')
 
# This code is contributed by avanitrachhadiya2155

C#

// C# code to reorder an array
// according to given indices
using System;
using System.Collections.Generic;
 
class GFG{
     
static int heapSize;
 
public static void heapify(int[] arr,
                           int[] index,
                           int i)
{
    int largest = i;
     
    // left child in 0 based indexing
    int left = 2 * i + 1;
      
    // right child in 1 based indexing
    int right = 2 * i + 2;
      
    // Find largest index from root,
    // left and right child
    if (left < heapSize &&
        index[left] > index[largest] )
    {
        largest = left;
    }
    if (right < heapSize &&
        index[right] > index[largest] )
    {
        largest = right;
    }
       
    if (largest != i)
    {
         
        // Swap arr whenever index is swapped
        int temp = arr[largest];
        arr[largest] = arr[i];
        arr[i] = temp;
          
        temp = index[largest];
        index[largest] = index[i];
        index[i] = temp;
          
        heapify(arr, index, largest);
    }
}
   
public static void heapSort(int[] arr,
                            int[] index,
                            int n)
{
     
    // Build heap
    for(int i = (n - 1) / 2 ; i >= 0 ; i--)
    {
        heapify(arr, index, i);
    }
      
    // Swap the largest element of
    // index(first element)
    // with the last element
    for(int i = n - 1 ; i > 0 ; i--)
    {
        int temp = index[0];
        index[0] = index[i];
        index[i] = temp;
          
        // Swap arr whenever index
        // is swapped
        temp = arr[0];
        arr[0] = arr[i];
        arr[i] = temp;
          
        heapSize--;
        heapify(arr, index, 0);
    }
}
 
// Driver Code
static void Main()
{
    int[] arr = { 50, 40, 70, 60, 90 };
    int[] index = { 3, 0, 4, 1, 2 };
    int n = arr.Length;
      
    heapSize = n;
    heapSort(arr, index, n);
      
    Console.WriteLine("Reordered array is: ");
    for(int i = 0 ; i < n ; i++)
        Console.Write(arr[i] + " ");
          
    Console.WriteLine();
      
    Console.WriteLine("Modified Index array is: ");
    for(int i = 0; i < n; i++)
        Console.Write(index[i] + " ");
}
}
 
// This code is contributed by divyesh072019

Javascript


输出:

Reordered array is: 
40 60 90 50 70 
Modified Index array is: 
0 1 2 3 4

时间复杂度: O(nlogn)

解决问题的另一种方法是 O(1) 的空间复杂度是:-

交换 arr 中的元素,直到 index_arr[i] 不等于 i。

让我们为给定的输入干运行以下代码:-

C++

// A O(n) time and O(1) extra space C++ program to
// sort an array according to given indexes
#include 
 
using namespace std;
 
// Function to reorder elements of arr[] according
// to index[]
void reorder(int arr[], int index_arr[], int n)
{
    // Fix all elements one by one
    for (int i = 0; i < n; i++) {
        // While index[i] and arr[i] are not fixed
        while (index_arr[i] != i) {
            swap(arr[i], arr[index_arr[i]]);
            swap(index_arr[i], index_arr[index_arr[i]]);
        }
    }
}
 
// Driver program
int main()
{
    int arr[] = { 50, 40, 70, 60, 90 };
    int index[] = { 3, 0, 4, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    reorder(arr, index, n);
 
    cout << "Reordered array is: \n";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
 
    cout << "\nModified Index array is: \n";
    for (int i = 0; i < n; i++)
        cout << index[i] << " ";
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)
输出
Reordered array is: 
40 60 90 50 70 
Modified Index array is: 
0 1 2 3 4