I have a piece of code which will find out the repeating elements in an array of size n where the elements satisfy 1 <= arr[i] <= n, the code is given below:
#include<stdio.h>
#include<stdlib.h>
void printTwoElements(int arr[], int size)
{
int i;
printf("\n The repeating element is");
for(i = 0; i < size; i++)
{
if(arr[abs(arr[i])-1] > 0)
{
arr[abs(arr[i])-1] = -arr[abs(arr[i])-1];
}
else
{
printf(" %d ", abs(arr[i]));
}
}
}
/* Driver program to test above function */
int main()
{
int arr[] = {7, 3, 4, 5, 5, 6, 2};
int n = sizeof(arr)/sizeof(arr[0]);
printTwoElements(arr, n);
return 0;
}
I would like to know the use of abs() in this given code?
In the course of the algorithm, some array entries are set to negative values as a marker. Therefore the entries’ absolute value has to be taken when they are used as indices into the array.
In the hope of not spoiling anything:
The algorithm requires that the array entries of an
n-element array all are between 1 andninclusive.If any entry is larger than
nor smaller than-nor 0, it will access invalid addresses, and if any element is negative, the marking logic will fail.The logic of the algorithm is:
So since array entries become negative in the course of running the algorithm, the absolute value has to be taken to obtain valid indices.
Let us follow the algorithm for a modified example to see how it works: