Sort 4 numbers without array

前端 未结 1 1813
无人及你
无人及你 2020-12-07 06:16

I have an exercise where I need to put 4 numbers in ascending order and then descending without using arrays. I can only use loops and if statements. I\'ve

相关标签:
1条回答
  • A nice way to do small, fixed-size sorts is using a sorting network:

    int tmp;
    if (a > b) { tmp = a; a = b; b = tmp; }
    if (c > d) { tmp = c; c = d; d = tmp; }
    if (a > c) { tmp = a; a = c; c = tmp; }
    if (b > d) { tmp = b; b = d; d = tmp; }
    if (b > c) { tmp = b; b = c; c = tmp; }
    

    Each line codes a comparison and swap between two elements.

    You can use this page to generate optimal sorting networks for small numbers of inputs.

    To sort in reverse order, just flip the > signs to < signs.

    0 讨论(0)
提交回复
热议问题