Odd and even sorting is a more personalized sorting. The basic idea is to arrange odd sequences in one order, even sequences in one order, then odd sequences in another, and even sequences in one order until all are ordered.
Let's give an example,
Array to be sorted
[6 2 4 1 5 9]
The first time comparing an odd sequence, the odd sequence is compared with its neighbors even sequence, such as 6 and 2, 4 and 1, 5 and 9
[6 2 4 1 5 9]
After exchange it becomes
[2 6 1 4 5 9]
The second comparison of even numbers is 6 and 1, and 5 and 5 are
[2 6 1 4 5 9]
After exchange it becomes
[2 1 6 4 5 9]
The third trip is an odd number, and the 2, 6, and 5 are selected to compare with their neighbor columns respectively.
[2 1 6 4 5 9]
After the exchange
[1 2 4 6 5 9]
The fourth even numbered series
[1 2 4 6 5 9]
One exchange
[1 2 4 5 6 9]
Java implementation:
static void oddEvensort(int[] ary) { //Parity sort boolean flag = true; while (flag) { boolean odd = false, even = false; for (int i = 0; i < ary.length - 1; i+=2) { if (ary[i] > ary[i + 1]) { ary[i] = ary[i + 1] + 0 * (ary[i + 1] = ary[i]); odd = true; } } for (int i = 1; i < ary.length - 1; i+=2) { if (ary[i] > ary[i + 1]) { ary[i] = ary[i + 1] + 0 * (ary[i + 1] = ary[i]); even = true; } } flag = odd || even; //If false, it means that no matter whether the odd or even sequence is the case, there is no comparison that meets the conditions} } The above flag = odd || even; has a true, indicating that it is still swapping. In the end, the flag is false only if all are false.
Rewriting it to flag = odd && even; If there is a false, the overall loop will no longer be completed. Like bubble sorting, it can reduce the last inner loop.