0

I am trying to sort a multidimensional array in ascending order. What am i doing wrong?

  for (i=0; i in avg; i++)
        for (j=0; j<=i; j++)
           if (avg[j]>avg[j+1])
           {
                temp=a[j];
                avg[j]=a[j+1];
                avg[j+1]=temp;         
           }

Sample input 1.43 2.14 1.57

Exped output 1.43 1.57 2.14

5
  • it didn't work i have the feeling that i am not referencing elements the propper way Commented Feb 24, 2017 at 21:56
  • is bubble sort ? are a and avg arrays differents? Commented Feb 24, 2017 at 21:56
  • please give sample input and expected o/p Commented Feb 24, 2017 at 21:58
  • yep my bad but it still does not work Commented Feb 24, 2017 at 21:59
  • 1
    where are the multiple dimensions? Commented Feb 24, 2017 at 22:48

3 Answers 3

3

Your array is not multidimensional. In any case, to sort an array using GNU awk for "sorted_in":

$ awk 'BEGIN{
    split("1.43 2.14 1.57",a)

    print "ascending:"
    PROCINFO["sorted_in"]="@val_num_asc"
    for (i in a) print a[i]

    print "\ndescending:"
    PROCINFO["sorted_in"]="@val_num_desc"
    for (i in a) print a[i]
}'
ascending:
1.43
1.57
2.14

descending:
2.14
1.57
1.43
Sign up to request clarification or add additional context in comments.

1 Comment

^1 nice presentation of sorted_in.
1

You are using bubble sorting, you have several errors .... I show an example working

awk '
    BEGIN{
    n = split("1.43 2.14 1.57", avg, " ")
    for (i=1; i<=n-1; ++i)
        for (j=i+1; j<=n; ++j)
            if (avg[i]>avg[j]){
                temp=avg[j]
                avg[j]=avg[i]
                avg[i]=temp        
            }
    for (i=1; i<=n; ++i) printf "%s%s",avg[i],(i==n?ORS:OFS)
}'

you get,

1.43 1.57 2.14

Comments

1

Also, if you have access to gawk extensions you can use asort() :

awk 'BEGIN{
        a[1]=1.43;
        a[2]=2.14;
        a[3]=1.57; 

        n = asort(a); 

        for(j = 1; j <= n; j++) { 
            print a[j] 
        }
     }'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.