fork download
  1. #include <cstdio>
  2. #include <algorithm>
  3.  
  4. #define XOR_SWAP(x,y) do { x ^= y; y ^= x; x ^= y; } while (0)
  5.  
  6. // Quicksort with XOR_SWAP
  7. void qsort1(int *a, int lo, int hi) {
  8. if (lo >= hi) { return; }
  9.  
  10. int pivot = a[hi];
  11. int i = lo-1;
  12.  
  13. for (int j = lo; j <= hi; j++) {
  14. if (a[j] <= pivot) {
  15. i = i+1;
  16. XOR_SWAP(a[i], a[j]);
  17. }
  18. }
  19.  
  20. qsort1(a, lo , i-1);
  21. qsort1(a, i+1, hi );
  22. }
  23.  
  24. // Quicksort with std::swap
  25. void qsort2(int *a, int lo, int hi) {
  26. if (lo >= hi) { return; }
  27.  
  28. int pivot = a[hi];
  29. int i = lo-1;
  30.  
  31. for (int j = lo; j <= hi; j++) {
  32. if (a[j] <= pivot) {
  33. i = i+1;
  34. std::swap(a[i], a[j]);
  35. }
  36. }
  37.  
  38. qsort2(a, lo , i-1);
  39. qsort2(a, i+1, hi );
  40. }
  41.  
  42. int main(int argc, char **args) {
  43. int test1[] = { 10, 7, 3, 9, 4, 1, 2, 6, 5, 8 };
  44. int test2[] = { 10, 7, 3, 9, 4, 1, 2, 6, 5, 8 };
  45.  
  46. qsort1(test1, 0, 9);
  47. qsort2(test2, 0, 9);
  48.  
  49. std::printf("\nTest 1 (XOR swap):\n\n");
  50. for (int i = 0; i < 10; i++) {
  51. std::printf("%d\n", test1[i]);
  52. }
  53.  
  54. std::printf("\nTest 2 (std::swap):\n\n");
  55. for (int i = 0; i < 10; i++) {
  56. std::printf("%d\n", test2[i]);
  57. }
  58. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
Test 1 (XOR swap):

1
2
0
0
5
0
0
8
9
10

Test 2 (std::swap):

1
2
3
4
5
6
7
8
9
10