C Exercises: Rearrange an array such that arr[i]=i
101. Rearrange Array so that arr[i] = i
Write a program in C to rearrange an array such that arr[i]=i.
N.B.: Given array contains N elements, from 0 to N – 1. All elements within the range may not be present in the array. There will be -1 if an element within the range is not present in the array.
Expected Output:
The given array is:
2 5 -1 6 -1 8 7 -1 9 1
The new array is: -1 1 2 -1 -1 5 6 7 8 9
The task is to write a C program that rearranges an array such that each element at index i equals i. If an element within the range [0, N-1] is not present in the array, it should be represented by -1. The program should iterate through the array, reposition elements to satisfy the condition arr[i] = i , and display the modified array.
Sample Solution:
C Code:
#include<stdio.h>
// Function to rearrange the array
int arrayRearrange(int arr1[], int l)
{
for (int i = 0; i < l; i++)
{
if (arr1[i] != -1 && arr1[i] != i)
{
int x = arr1[i];
// Swap elements until an element is -1 or the same as its index
while (arr1[x] != -1 && arr1[x] != x)
{
int y = arr1[x];
arr1[x] = x;
x = y;
}
arr1[x] = x;
if (arr1[i] != i)
{
arr1[i] = -1; // Set the element to -1 if it doesn't match its index
}
}
}
}
int main()
{
int arr1[] = { 2, 5, -1, 6, -1, 8, 7, -1, 9, 1 };
int n = sizeof(arr1) / sizeof(arr1[0]);
int i = 0;
// Print the original array
printf("The given array is: \n");
for(i = 0; i < n; i++)
{
printf("%d ", arr1[i]);
}
printf("\n");
// Rearrange the array and print the new array
printf("The new array is: ");
arrayRearrange(arr1, n);
for (int i = 0; i < n; i++)
printf("%d ",arr1[i]);
}
Output:
The given array is: 2 5 -1 6 -1 8 7 -1 9 1 The new array is: -1 1 2 -1 -1 5 6 7 8 9
Visual Presentation:
Flowchart:/p>
For more Practice: Solve these Related Problems:
- Write a C program to rearrange an array so that each element equals its index, filling missing positions with -1.
- Write a C program to update an array based on the mapping arr[i] = arr[arr[i]] and then fix missing indices.
- Write a C program to rearrange the array using in-place swaps such that arr[i] becomes i, using minimal extra space.
- Write a C program to rearrange an array so that each index is filled with the correct value or -1 if absent, using recursion.
Go to:
PREV : Count Number of Clumps.
NEXT : Alternate Small, Large, Second Smallest, Second Largest, etc.
C Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.