我想出了两种方法来做你的“同时”排序。
详细阅读代码,我认为很容易理解:
BEGIN{
a[1]="5"; b[1]="fifth"
a[2]="3"; b[2]="third"
a[3]="6"; b[3]="sixth"
#method 1: combine the two arrays before sort
for(;++i<=3;)
n[i] = a[i]" "b[i]
asort(n)
print "--- method 1: ---"
for(i=0;++i<=3;)
print n[i]
#method 2:
#here we build a new array/hastable, and use asorti()
for(i=0;++i<=3;)
x[a[i]]=b[i]
asorti(x,t)
print "--- method 2: ---"
for(i=0;++i<=3;)
print t[i],x[t[i]]
}
输出:
kent$ awk -f sort.awk
--- method 1: ---
3 third
5 fifth
6 sixth
--- method 2: ---
3 third
5 fifth
6 sixth
编辑
如果要获取原始索引,可以尝试以下方法3:
#method 3:
print "--- method 3: ---"
for(i=0;++i<=3;)
c[a[i]] = i;
asort(a)
for(i=0;++i<=3;)
print a[i], " | related element in b: "b[c[a[i]]], " | original idx: " c[a[i]]
输出是:
--- method 3: ---
3 | related element in b: third | original idx: 2
5 | related element in b: fifth | original idx: 1
6 | related element in b: sixth | original idx: 3
你可以看到,原来的 idx 在那里。如果要将它们保存到数组中,只需添加idx[i]=c[a[i]]
for 循环。
编辑2
方法4:以不同的顺序组合,然后拆分得到idx数组:
#method 4:
for(i=0;++i<=3;)
m[i] = a[i]"\x99"i
asort(m)
print "--- method 4: ---"
for(i=0;++i<=3;){
split(m[i],x,"\x99")
ind[i]=x[2]
}
#test ind array:
for(i=0;++i<=3;)
print i"->"ind[i]
输出:
--- method 4: ---
1->2
2->1
3->3