Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to rearrange an array and set arr[i] to arr[arr[index]] to index in C#

1 Answer

0 votes
using System;

public class MyClass {
	public static void rearrange_array(int[] arr) {
		int size = arr.Length;

		for (int i = 0; i < size; i++) {
			arr[i] += (arr[arr[i]] % size) * size;
		}

		for (int i = 0; i < size; i++) {
			arr[i] /= size;
		}
	}
	public static void Main(string[] args)
	{
		int[] arr = new int[] {3, 5, 0, 2, 1, 4};

		// arr[arr[0]] = 2 -> arr[0] = 2
		// arr[arr[1]] = 4 -> arr[1] = 4
		// arr[arr[2]] = 3 -> arr[2] = 3
		// arr[arr[3]] = 0 -> arr[3] = 0
		// arr[arr[4]] = 5 -> arr[4] = 5
		// arr[arr[5]] = 1 -> arr[5] = 1

		rearrange_array(arr);

		foreach (int val in arr) {
			Console.Write(val + " ");
		}
	}
}




/*
run:
 
2 4 3 0 5 1 
 
*/

 



answered Aug 17, 2022 by avibootz
...