ar[j]) { int temp = ar[i]; ar[i] = ar[j]; ar[...">
📜 ⬆️ ⬇️

Single-row sorting

We have the usual "bubble":
for(int i = 0; i < n - 1; i++ ) for(int j = i + 1; j < n; j++) if(ar[i] > ar[j]) { int temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; } 


Problem number 1: Get rid of the temporary variable. This is done like this:

 ar[i] ^= ar[j] ^= ar[i] ^= ar[j]; 

')
Problem number 2: Get rid of if.
It makes it even easier:
 (ar[i] > ar[j]) ? ar[i] ^= ar[j] ^= ar[i] ^= ar[j] : 0; 


Task number 3: Basic. Get rid of the inner for for j loop.
To do this: 1) Iterate from j to n, while in the condition always return true 2) Check the condition of the end of the algorithm only when the entire iteration on j has passed
3) When checking the conditions, do j = i + 1, i = i + 1.
The result is:
 for(int i = 0, j = 0; j < n ? 1 : i < n - 1; j = j < n ? ((ar[i] > ar[j] ? ar[i] ^= ar[j] ^= ar[i] ^= ar[j] : 0), ( j + 1 )) : ++i //  j=n,     ); 


Source code

Source: https://habr.com/ru/post/144510/


All Articles