奇偶排序的方法是,先从数组下标为奇数的开始计算,奇数和偶数进行比较交换。然后从偶数开始计算,偶数和奇数再进行比较交换。一直到数组是排序的结束。
package com.bplead.sort; public class BatcherSort { public static void main(String[] args) { int array[] = {43,24,12,56,78,9,67,50}; boolean sorted = false; print(array); while(!sorted){ sorted = true; //odd for(int i=1;i<array.length-1;i+=2){ if(array[i]>array[i+1]){ swap(array,i,i+1); sorted = false; } } print(array); for(int i=0;i<array.length-1;i+=2){ if(array[i]>array[i+1]){ swap(array,i,i+1); sorted = false; } } print(array); } } private static void swap(int[] array,int i,int j){ int temp = array[i]; array[i] = array[j]; array[j] = temp; } private static void print(int[] a){ for(int i=0;i<a.length;i++) System.out.print(a[i] + " "); System.out.println(); } }
看看整个过程中交换的情况:
43 24 12 56 78 9 67 50
43 12 24 56 78 9 67 50
12 43 24 56 9 78 50 67
12 24 43 9 56 50 78 67
12 24 9 43 50 56 67 78
12 9 24 43 50 56 67 78
9 12 24 43 50 56 67 78
9 12 24 43 50 56 67 78
9 12 24 43 50 56 67 78