Rearrange an array so that arr [ i ] becomes arr [ arr [ i ] ] with O ( 1 ) extra space | C # Program to rearrange an array so that arr [ i ] becomes arr [ arr [ i ] ] with O ( 1 ) extra space ; Function to rearrange an array in - place so that arr [ i ] becomes arr [ arr [ i ] ] . ; First step : Increase all values by ( arr [ arr [ i ] ] % n ) * n ; Second Step : Divide all values by n ; A utility function to print an array of size n ; Driver Code
using System ; class Rearrange { void rearrange ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) arr [ i ] += ( arr [ arr [ i ] ] % n ) * n ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] /= n ; } void printArr ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; Console . WriteLine ( " " ) ; } public static void Main ( ) { Rearrange rearrange = new Rearrange ( ) ; int [ ] arr = { 3 , 2 , 0 , 1 } ; int n = arr . Length ; Console . Write ( " Given ▁ Array ▁ is ▁ : " ) ; rearrange . printArr ( arr , n ) ; rearrange . rearrange ( arr , n ) ; Console . Write ( " Modified ▁ Array ▁ is ▁ : " ) ; rearrange . printArr ( arr , n ) ; } }