c++ - swap function in quick sort gives wrong output -
swap function quick sort. gives wrong output. when use temporary variable gives correct output. here tester:
void swap(int &a,int &b){ a=a+b; b=a-b; a=a-b; }
this works fine though:
void swap(int &a,int &b){ int temp=a; a=b; b=a; }
i passing array elements function inside partition function of quick sort algorithm.
your code swap without 3rd variable looks ok. unfortunately, algorithm cannot applied swapping value itself, example:
void swap(int &a,int &b){ // &a == &b, value 123 a=a+b; // == b == 246 b=a-b; // == b == 0 (oops!) a=a-b; // == b == 0 }
also, please note there's standard function swapping (std::swap
) , code, if compiled without optimization, works slower usual swap (with 3rd variable) performs more memory operations. also, code may lead integer overflow or underflow undefined behavior standard , may or may not work expect. if add readability issue (the important thing) list, recommendation just don't use swap without 3rd variable.
Comments
Post a Comment