Rearrange an array such that arr[i] = i in C

Problem statement
Consider an array having N elements. Rearrange the array such that A[i] = i and if i is not present, replace it with -1 at that place. As not all elements in between 0 to N-1 will be present.

Naive Approach
Here we have used two for loops. One for traversing through numbers O to N-1 and the other for traversing through the array.

/*C code to Rearrange an array such that arr[i] = i*/
#include<stdio.h>

void reArrangeArray(int arr[], int n)
{
	int i, j, temp;


	for (i = 0; i < n; i++)
	{
		for (j = 0; j < n; j++)
		{
			if (arr[j] == i) {
				temp = arr[j];
				arr[j] = arr[i];
				arr[i] = temp;
				break;
			}
		}
	}

	for (i = 0; i < n; i++)
	{
		if (arr[i] != i)
		{
			arr[i] = -1;
		}
	}

	printf("\nArray after rearranging:\n");
	for (i = 0; i < n; i++) {
		printf("%d\t",arr[i]);
	}
}

int main()
{
	int n, arr[] = { -1, -1, 5, 1, 8, 3, 2, -1, 4, -1 };
	n = sizeof(arr) / sizeof(arr[0]);
	
	printf("Array is:\n");
	for (int i = 0; i < n; i++) {
		printf("%d\t",arr[i]);
	}
	
	reArrangeArray(arr, n);
}

Output

 gcc arri.c
$ ./a.out
Array is:
-1 -1 5 1 8 3 2 -1 4 -1
Array after rearranging:
-1 1 2 3 4 5 -1 -1 8 -1 $
Time complexity: O(n)

 also see

C Programming language
Go Programming language
Linked List Array
Simplification Queue
DBMS Reasoning
Aptitude HTML
Previous articleCyclically rotate an array by k elements in C
Next articleReverse a string using stack

LEAVE A REPLY

Please enter your comment!
Please enter your name here