3 numbers in ascending order WITHOUT the use of conditional statements in Java. As in I can't use if statements at all

前端 未结 6 1034
旧巷少年郎
旧巷少年郎 2021-01-25 00:24

My code looks like this so far:

public class ThreeSort {
    public static void main(String[] args) {

        int num1 = Integer.parseInt(args[0]);
        int          


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-25 01:16

    This is how I would implement three_sort without any if statements or ternary operators. You would have to adapt this to your language of choice.

    def two_sort(a, b):
        small = int(a < b)  * a + int(a >= b) * b
        large = int(a >= b) * a + int(a < b)  * b
        return small, large
    
    def three_sort(a, b, c):
        a, b = two_sort(a, b)
        a, c = two_sort(a, c)
        b, c = two_sort(b, c)
        return a, b, c
    

    for a more general solution:

    from random    import randint
    
    def two_sort(a, b):
        small = int(a < b)  * a + int(a >= b) * b
        large = int(a >= b) * a + int(a < b)  * b
        return small, large
    
        return li[-1]
    
    def n_sort(li):
        for _ in li:
            for i, _ in enumerate(li[:-1]):
                li[i], li[i+1] = two_sort(li[i], li[i+1])
        return li
    
    N = 10
    li = [randint(0, 1000) for _ in range(N)]
    print(N_Sort(N)(*li))
    

提交回复
热议问题