Single row sorting
We have the usual “bubble”:
Task number 1: Get rid of the temporary variable. This is done like this:
Task number 2: Get rid of if.
Made even easier:
Task number 3: Basic. Get rid of the inner for loop of j.
To do this: 1) Iterate from j to n, while always returning true in the condition 2) Check the end condition of the algorithm only when the whole iteration over j has passed
3) When checking the condition, do j = i + 1, i = i + 1.
The result is:
Source code
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;
}
Task number 1: Get rid of the temporary variable. This is done like this:
ar[i] ^= ar[j] ^= ar[i] ^= ar[j];
Task number 2: Get rid of if.
Made 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 loop of j.
To do this: 1) Iterate from j to n, while always returning true in the condition 2) Check the end condition of the algorithm only when the whole iteration over j has passed
3) When checking the condition, 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