根据给定的索引重新排列数组 [英] Reorder array according to given index
问题描述
根据给定索引的算法重新排序数组
Algorithm reorder array according to given index
a[] = [50, 40, 70, 60, 90]
index[] = [3, 0, 4, 1, 2]
a= [60,50,90,40,70]
在O(n)中且没有额外的数组/空间
in O(n) and With out extra array/spaces
推荐答案
您需要空间来存放临时变量和循环计数器/索引。根据算法,通常的重新排序还会将index []更改回{0,1,2,3,4}。
You'll need space for a temp variable and loop counters / indices. The usual "reorder" according to algorithm is also going to change index[] back to {0, 1, 2, 3, 4}.
提示,注意排序索引中的索引[]。
Hint, noting the ordering of indices in index[].
{0, 1, 2, 3, 4}
index[] = {3, 0, 4, 1, 2}
可以按照循环进行重新排序。以index [0]开头,如果您查看index [0],请注意循环,然后是index [index [0]],依此类推...
The reordering can be done by following the "cycles". Start with index[0], and note the "cycles" if you look at index[0], then index[index[0]], and so on ...
// 1st cycle
index[0] == 3 // cycle starts at 0
index[3] == 1
index[1] == 0 // end of cycle since back at 0
// 2nd cycle
index[2] == 4 // cycle starts at 2
index[4] == 2 // end of cycle since back at 2
示例C代码:
#include <stdio.h>
static int A[] = {50, 40, 70, 60, 90};
static int I[] = {3, 0, 4, 1, 2};
int main()
{
int i, j, k;
int tA;
/* reorder A according to I */
/* every move puts an element into place */
/* time complexity is O(n) */
for(i = 0; i < sizeof(A)/sizeof(A[0]); i++){
if(i != I[i]){
tA = A[i];
j = i;
while(i != (k = I[j])){
A[j] = A[k];
I[j] = j;
j = k;
}
A[j] = tA;
I[j] = j;
}
}
for(i = 0; i < sizeof(A)/sizeof(A[0]); i++)
printf("%d\n", A[i]);
return 0;
}
相同的算法,但是使用交换而不是移动(这是较慢的方法)
The same algorithm, but using swaps instead of moves (this is slower method).
#include <stdio.h>
#define swap(a, b) {(a)^=(b); (b)^=(a); (a)^=(b);}
static int A[] = {50, 40, 70, 60, 90};
static int I[] = {3, 0, 4, 1, 2};
int main()
{
int i, j, k;
/* reorder A according to I */
/* every swap puts an element into place */
/* last swap of a cycle puts both elements into place */
/* time complexity is O(n) */
for(i = 0; i < sizeof(A)/sizeof(A[0]); i++){
if(i != I[i]){
j = i;
while(i != (k = I[j])){
swap(A[j], A[k]);
I[j] = j;
j = k;
}
I[j] = j;
}
}
for(i = 0; i < sizeof(A)/sizeof(A[0]); i++)
printf("%d\n", A[i]);
return 0;
}
这篇关于根据给定的索引重新排列数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!