sorting array
Author Message
sorting array

Greets,
before some time I read in this newsgroup the following snippet:

!a[\$0]++   ;remove duplicated rows

so I used it for making array without duplicates:

Input: "zzz", "xxx", "yyy", "xxx", "zzz" etc
Output: array -> ["zzz","xxx","yyy"]

Problem: How to sort array with uniq strings?
Target array: ["xxx","yyy","zzz"]

Best Regards,
Sto

Sat, 08 Feb 2003 20:57:31 GMT
sorting array

Quote:

> !a[\$0]++   ;remove duplicated rows
> so I used it for making array without duplicates
> ...

That's a nice and tricky awk solution, but in the real world
one would use the system sort command with the 'unique keys'
switch, whichever it be (in unix  sort -u)

Quote:
> Problem: How to sort array with uniq strings?

The real world solution is to use external system sort command.

Another possible dirty solution is to make a function to build
a 'sort map' array (indexed by ordinal number) of the first
array (indexed by string key):

...
# mysortmap() builds ordered array oo[bumbers] from array
# aa[keys] and returns the number of elements in n
...
n = mysortmap(oo,aa)
...
for(i = 1; i <= n; i++) {
k = oo[i]
...
print aa[k]  # for example...
...
}
...

function mysortmap(oo,aa,   n,i,j,k)
{
# build a 'sort map' ordered array
n = 0
# fill in keys and count them
for(k in aa) {
oo[++n] = k
}
# silly sort with two nested loops
for(i = 1; i <= n -1; i++) {
k = i
for(j = i+1; j <= n; j++) { # fetch lowest element index k
if(oo[j] < oo[k]) k = j
}
if(k > i) { # swap k,i
j = oo[k]
oo[k] = oo[i]
oo[i] = j
}
}
return n

Quote:
}

--
All true believers shall break their eggs at the convenient end.

Sat, 08 Feb 2003 03:00:00 GMT

 Page 1 of 1 [ 2 post ]

Relevant Pages