C Exercises: Rearrange an array so that arr[i] becomes arr[arr[i]] from an array of size n and elements are in the range 0 to n-1
C Array: Exercise-90 with Solution
Given an array of size n such that every element is in the range from 0 to n-1. Write a program in C to rearrange the given array so that arr[i] becomes arr[arr[i]].
Sample Solution:
C Code:
#include<stdio.h>
void arrayArrange(int arr1[], int n)
{
for (int i=0; i < n; i++)
arr1[i] += (arr1[arr1[i]]%n)*n;
for (int i=0; i<n; i++)
arr1[i] /= n;
}
void arrayPrinting (int arr1[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", arr1[i]);
printf("\n");
}
int main()
{
int arr1[] = {2, 1, 4, 3, 0};
int n = sizeof(arr1)/sizeof(arr1[0]);
printf("The Original array is \n");
arrayPrinting(arr1, n);
arrayArrange(arr1, n);
printf("The modified array is: \n");
arrayPrinting(arr1, n);
return 0;
}
Sample Output:
The Original array is 2 1 4 3 0 The modified array is: 4 1 0 3 2
Flowchart:
![Flowchart: Rearrange an array so that arr[i] becomes arr[arr[i]] from an array of size n and elements are in the range 0 to n-1](https://www.w3resource.com/w3r_images/c-array-exercise-flowchart-90.png)
C Programming Code Editor:
Improve this sample solution and post your code through Disqus.
Previous: Write a program in C to find maximum size square sub-matrix with all 1s.
Next: Given an unsorted array of specific size. Write a program in C to find the minimum length of subarray such that,ssorting this subarray makes the whole array sorted.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
C Programming: Tips of the Day
C Programming - What is the argument for printf that formats a long?
Put an l (lowercased letter L) directly before the specifier.
unsigned long n; long m; printf("%lu %ld", n, m);
Ref : https://bit.ly/3dIwfkP
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises