Possible bug in STD C quicksort. Am i missing something ?

后端 未结 1 1687
星月不相逢
星月不相逢 2021-01-24 06:04

xorshift init: 7731

A: 2064221648 1036493097 633233112 583013546 721278080 -1646392714 -829660162 478401127

E: 583013546 633233112 721278080 10

1条回答
  •  野的像风
    2021-01-24 06:43

    Compiled with

    gcc sort.c -Wall -Wextra
    

    There was one error about not matching conversion specifier (unsigned int requires %u but you had %lld - possibly typo for %11d but even then it were wrong.

    Running, I get sometimes correct output, sometimes not. So I compiled with -fsanitize=undefined, and

    sort.c:11:13: runtime error: signed integer overflow: 
        1288106901 - -1003011281 cannot be represented in type 'int'
    E: 
      290879035
      591885416
      767444883
     1288106901
     1955087149
    -1509681722
    -1289472872
    -1003011281
    

    I.e. your smart code wasn't too smart there. The correct way to return a value from the comparison function would be

    return x < y ? -1 : x > y ? 1 : 0;
    

    or

    return (x > y) - (x < y);
    

    as suggested by HolyBlackCat

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