sorting int array with only 3 elements

后端 未结 4 949
一个人的身影
一个人的身影 2020-12-09 11:56

I have this array:

int [] myarray =  {17, 6, 8};

What is the optimal way to sort this array, in pseudocode?

Thanks!

4条回答
  •  旧时难觅i
    2020-12-09 12:19

    This code makes 2 or 3 comparisons and 4 memory records in the worst case, as opposed to another answer (always 3 comparisons and 9 memory records in the worst case).

    if a[0] < a[1]:
        if a[1] > a[2]:
            if a[0] < a[2]:
                temp = a[1]
                a[1] = a[2]
                a[2] = temp
            else:
                temp = a[0]
                a[0] = a[2]
                a[2] = a[1]
                a[1] = temp
        else:
            # do nothing
    else:
        if a[1] < a[2]:
            if a[0] < a[2]:
                temp = a[0]
                a[0] = a[1]
                a[1] = temp
            else:
                temp = a[0]
                a[0] = a[1]
                a[1] = a[2]
                a[2] = temp
        else:
            temp = a[0]
            a[0] = a[2]
            a[2] = temp
    

提交回复
热议问题