sorting int array with only 3 elements

北慕城南 提交于 2019-12-17 18:54:51

问题


I have this array:

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

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

Thanks!


回答1:


I think this should be quite fast (ascending order):

if (el1 > el2) Swap(el1,el2)
if (el2 > el3) Swap(el2,el3)
if (el1 > el2) Swap(el1,el2)



回答2:


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



回答3:


Slightly more efficient version than the unrolled bubble sort, not optimal, but still quite simple

if (el1 > el2) Swap(el1, el2)
if (el2 > el3) {
   Swap(el2, el3)
   if (el1 > el2) Swap(el1, el2)
}



回答4:


May this graphic showing a decision tree for sorting three elements helps:



来源:https://stackoverflow.com/questions/4793251/sorting-int-array-with-only-3-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!