This article describes the parity sorting algorithm of Java data structure and algorithm. Share it for your reference, as follows:
Algorithm ideas:
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]
Specific code:
public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { int[] numbers = new int[]{12,33,45,33,13,55,34,7,6}; Main.oddEventSort(numbers); for(int i=0; i<numbers.length; i++){ System.out.print(numbers[i]+" "); } } private static void oddEventSort(int[] numbers){ int temp; for(int i=numbers.length-1; i>numbers.length/2-1; i--){ for(int j=1; j<=i; j+=2){ if(j==numbers.length-1)break; if(numbers[j]>numbers[j+1]){ temp = numbers[j]; numbers[j] = numbers[j+1]; numbers[j+1] = temp; } } for(int j=0; j<=i; j+=2){ if(j==numbers.length-1)break; if(numbers[j]>numbers[j+1]){ temp = numbers[j]; numbers[j] = numbers[j+1]; numbers[j+1] = temp; } } } } }}PS: It is said that this algorithm is easier to use in the multi-core era
For more information about Java algorithms, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.