Home >Backend Development >C++ >Rearrange an array so that 'arr' becomes 'i' if 'arr' is 'j' in C++
Input− int arr[] = {3, 4, 1, 2, 0}
Output− Array before sorting: 3 4 1 2 0 Rearrange the array so that arr[j] becomes i. If arr[i] is j, it is: 4 2 3 0 1
Explanation− We get an integer of size Array 6 and all elements in the array with values less than 6. Now, we will rearrange the array, i.e. arr[1] is 4, arr[4] = 1; arr[2] is 1, arr[1] = 2; arr[3] is 2. arr[2] = 3; arr[4] is 0, arr[0]=4. Therefore, the final array is 4 2 3 0 1.
Input t− int arr[] = {2, 0, 1, 3}
Output− Array before arrangement: 2 0 1 3 Rearrange the array so that arr[j] becomes i, if arr[i] is j, then: 1 2 0 3
Explanation− We get an integer of size 6 array and the value of all elements in the array is less than 6. Now, we will rearrange the array, i.e. arr[0] is 2, arr[2] = 0; arr[1] is 0, arr[0] = 1; arr[2] is 1, arr[1] = 2; arr[3] is 3, arr[3] = 3. Therefore, the final array is 1 2 0 3.
Input an array of integer type elements and calculate the size of the array.
Print the array before arranging it and call the function Rearrangement(arr, size)
In the function Rearrangement(arr, size)
Create an array ptr[] of integer type values with the same size as the array arr[].
Start looping FOR from i to 0 until i is less than size. Inside the loop, set ptr[arr[i]] to i.
Start looping FOR from i to 0 until i is less than size. Inside the loop, set arr[i] to ptr[i].
#Print the rearranged array.
#include <bits/stdc++.h> using namespace std; void Rearrangement(int arr[], int size){ int ptr[size]; for(int i = 0; i < size; i++){ ptr[arr[i]] = i; } for(int i = 0; i < size; i++){ arr[i] = ptr[i]; } } int main(){ //input an array int arr[] = {3, 4, 1, 2, 0}; int size = sizeof(arr) / sizeof(arr[0]); //print the original Array cout<<"Array before Arrangement: "; for (int i = 0; i < size; i++){ cout << arr[i] << " "; } //calling the function to rearrange the array Rearrangement(arr, size); //print the array after rearranging the values cout<<"\nRearrangement of an array such that ‘arr[j]’ becomes ‘i’ if ‘arr[i]’ is ‘j’ is: "; for(int i = 0; i < size; i++){ cout<< arr[i] << " "; } return 0; }
If we run the above code it will generate the following output
Array before Arrangement: 3 4 1 2 0 Rearrangement of an array such that ‘arr[j]’ becomes ‘i’ if ‘arr[i]’ is ‘j’ is: 4 2 3 0 1
The above is the detailed content of Rearrange an array so that 'arr' becomes 'i' if 'arr' is 'j' in C++. For more information, please follow other related articles on the PHP Chinese website!