简体   繁体   English

在 C 中,为什么将 x 与 y 交换比将 y 与 x 交换更快?

[英]In C, why swapping x with y is faster then swapping y with x?

In a problem minimum-swaps-2 , arr is unsorted array, arr_count is number of array elements, we need to return minimum number of swaps to sort the array,在一个minimum- swaps -2 问题中,arr 是未排序的数组,arr_count 是数组元素的数量,我们需要返回最小交换次数来对数组进行排序,

i tried:我试过:

int minimumSwaps(int arr_count, int* arr) {
    int swap = 0;
    for(int i  = 0; i < arr_count;){
        if(arr[i] != (i + 1)){
            int temp = arr[i];
            arr[i] = arr[arr[i] - 1];
            arr[arr[i] - 1] = temp;
            swap++;
        } else {
            i++;
        }
    }
    return swap;
}

but it didn't work.但它没有用。 It shows time out error.它显示超时错误。 ie it took more time to run!即运行需要更多时间! Then i tried the below code, it worked!然后我尝试了下面的代码,它奏效了!

        int temp = arr[arr[i] - 1];
        arr[arr[i] - 1] = arr[i];
        arr[i] = temp;
        swap++;

The only difference between both is swapping x with y or y with x.两者之间的唯一区别是将 x 与 y 或 y 与 x 交换。 What difference does it make?它有什么区别?

After arr[i] = arr[arr[i] - 1];arr[i] = arr[arr[i] - 1]; the value arr[i] was changed and arr[arr[i] - 1] doesn't point at same storage anymore, arr[arr[i] - 1] = temp;arr[i]已更改并且arr[arr[i] - 1]不再指向相同的存储, arr[arr[i] - 1] = temp; writes to wrong storage.写入错误的存储。

So you actually do not swap two values.所以你实际上不会交换两个值。 It could be obvious if you represented it as pointer arithmetic.如果您将其表示为指针算术,则可能很明显。

        int temp = *(arr + i);
        *(arr + i) = *(arr + temp - 1);
        *(arr + *(arr + i) - 1) = temp;

Last line equals to *(arr + *(arr + temp - 1) - 1) with values present at moment before line 2 execution, which IS wrong by definition of task.最后一行等于*(arr + *(arr + temp - 1) - 1)值出现在第 2 行执行之前,根据任务的定义这是错误的。

In fact it gives obvious solution:事实上,它给出了明显的解决方案:

        int temp = *(arr + i);
        *(arr + i) = *(arr + temp - 1);
        *(arr + temp - 1) = temp;

or或者

        int temp = arr[i];
        arr[i] = arr[temp - 1];
        arr[temp - 1] = temp;

Which yields result of 5 returned from minimumSwaps .这产生从minimumSwaps返回的结果 5 。

Essentially you time-outed because first variant unable to reach solution.基本上你超时是因为第一个变体无法达成解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM