1

There is a question as follows: Rearrange an array such that arr[i] = i , and if i is not present in the array, set it to -1. Here is the solution of the question:

int main() {
    int arr[] = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1};
    int n = sizeof(arr) / sizeof(arr[0]);
    for (int i = 0; i < n;) {
        if (arr[i] >= 0 && arr[i] != i)
            arr[arr[i]] = (arr[arr[i]] + arr[i]) -
                          (arr[i] = arr[arr[i]]);
        else
            i++;
    }

    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

I am not getting what arr[arr[i]] = (arr[arr[i]] + arr[i]) - (arr[i] = arr[arr[i]]) line means. Why are we assigning arr[i] a new value ?

Why don't we subtract directly?

anastaciu
  • 23,467
  • 7
  • 28
  • 53
  • 6
    Other than that, this is a sequencing violation and undefined behavior. You should let your teacher know. – S.S. Anne May 02 '20 at 21:42
  • 1
    That line is a (terrible) way of swapping the value of the two variables `arr[arr[i]]` and `arr[i]`. It's considered a trick to swap them without introducing a temporary variable, which is the normal (and correct!) way of doing it. Have a look at this answer for an explanation: https://stackoverflow.com/a/21486007/3982001. But don't miss the comment that shows that it's wrong, as the result is not reliable! So it is both very hard to understand and wrong. Don't do it! – Fabio says Reinstate Monica May 02 '20 at 21:59
  • This program is fun to read out loud in a pirate voice, especially if you pronounce `i` as "aye". – Nate Eldredge May 02 '20 at 22:29
  • Thanks for your answer. One more thing confuses me, while we are swapping, how can we make sure that a [ a [ i ] ] actually exists? It is possible that value of a [i ] = 10 (for example ) , but array comprises of only 7 elements. In that case, a [ a [ i ] ] won't even exist and we are using it for swapping in code. Shouldn't it throw an error? – SHIVANSHI VERMA May 03 '20 at 04:45
  • 1
    You are right, the program could crash. It's making assumptions about the data. If you know for sure that the values will never exceed the size of the array (well, minus 1, to be precise), everything is fine. Otherwise you must check. – Fabio says Reinstate Monica May 03 '20 at 19:16

0 Answers0