Biggest and smallest of four integers (No arrays, no functions, fewest 'if' statements)

后端 未结 18 2544
北海茫月
北海茫月 2020-12-10 11:29

You see, I\'ve self-taught myself C++ (not completely, I\'m still procrastinating -_-). So, now I started university and they\'re teaching C and they made us do a program of

18条回答
  •  醉酒成梦
    2020-12-10 12:14

    Do a "manual" merge sort, or well, just the second bit of it:

    Conceptually, a merge sort works as follows

    1. Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
    2. Repeatedly merge sublists to produce new sublists until there is only 1 sublist remaining. This will be the sorted list.

    Merge sort merging step illustration

    Code:

    int a = 5, b=4, c=7, d=9;
    int min_ab, min_cd, min;
    min_ab = a < b ? a : b;
    min_cd = c < d ? c : d;
    min = min_ab < min_cd ? min_ab : min_cd;
    printf("%d", min);
    

    .. and similarly for max.

    If you prefer, you can expand the ternary operator into if (a < b) { min_ab = a; } else { min_ab = b; } (spread over multiple lines for readability).

    Merge sort has a complexity of O(n*log(n)), so you should at most need O(n*log(n)) ifs (see the wikipedia article on merge sort). According to Wikipedia, "... These are all comparison sorts, and so cannot perform better than O(n log n) in the average or worst case" (source), so I think this shouldn't be too far off in terms of minimum number of ifs.. Though you could try to see if manually performing one of the other algorithms results in fewer ifs ;-).

提交回复
热议问题