算法思路:
在数组中重复两趟扫描。第一趟扫描选择所有的数据项对,a[j]和 a[j+1], j 是奇数(j=1, 3, 5,…)。如果它们的关键字的值次序颠倒,就交换它们。第二趟扫描对所有的偶数数据项进行同样的操作(j=0, 2, 4, 6,…)。重复进行这样两趟的排序直到数组全部有序。
注:奇偶排序实际上在多处理器环境中很有用,处理器可以分别同时处理每一个奇数对,然后又同时处理偶数对。因为奇数对是彼此独立的,每一对都可以用不同的处理器比较和交换。这样可以快速地排序。
自己的理解:
不断比较相邻两个数据(根据奇数对和偶数对来比较),进行一趟就能把大的那个数移动到下一位,小的那个数移动到前一位,奇偶数对交替,重复执行,直到数据排列好
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //奇偶排序 2 class ArrayOddEven 3 { 4 private long[] a; 5 private int nElems; 6 //-------------------------------------------------------------- 7 public ArrayOddEven(int max) //构造方法 8 { 9 a = new long[max]; //定义一个数组 10 nElems = 0; 11 } 12 //-------------------------------------------------------------- 13 public void insert(long value) //插入数据 14 { 15 a[nElems] = value; 16 nElems++; 17 } 18 //-------------------------------------------------------------- 19 public void display() //显示数组 20 { 21 for(int j=0; j<nElems; j++) 22 System.out.print(a[j] + " "); 23 System.out.println(""); 24 } 25 //-------------------------------------------------------------- 26 public void oddEvenSort()//执行奇偶排序 27 { 28 boolean flag = false ; 29 while(!flag) 30 { 31 flag = true ; 32 for(int i=1 ; i<a.length-1 ; i+=2)//奇数 33 if(a[i]>a[i+1]) 34 { 35 swap(i,i+1) ; 36 flag = false ; 37 } 38 39 for(int i=0 ; i<a.length-1 ; i+=2)//偶数 40 if(a[i]>a[i+1]) 41 { 42 swap(i,i+1) ; 43 flag = false ; 44 } 45 } 46 } 47 //-------------------------------------------------------------- 48 private void swap(int one, int two) //交换方法 49 { 50 long temp = a[one]; 51 a[one] = a[two]; 52 a[two] = temp; 53 } 54 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //测试程序 2 public class OddEvenSortApp2 3 { 4 public static void main(String[] agrs) 5 { 6 7 int maxSize = 10 ; 8 ArrayOddEven theArray = new ArrayOddEven(maxSize) ; 9 for(int j=0; j<maxSize; j++) // fill array with random numbers 10 { 11 long n = (long)( java.lang.Math.random()*(100) ); 12 theArray.insert(n); 13 } 14 theArray.display() ; 15 System.out.println("OddEvenSort...") ; 16 theArray.oddEvenSort() ; 17 theArray.display() ; 18 } 19 }
参考:
别人写的代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public static void oddEvenSort(int[] array) { 2 boolean unsorted = true; 3 while (unsorted) { 4 unsorted = false; 5 int i = 1; 6 boolean oddUnsorted = scan(array, i); 7 i = 0; 8 boolean evenUnsorted = scan(array, i); 9 unsorted = oddUnsorted || evenUnsorted; 10 } 11 } 12 13 private static boolean scan(int[] array, int i) { 14 boolean unsorted = false; 15 while (i < array.length - 1) { 16 if (array[i] > array[i + 1]) { 17 swap(array, i, i + 1); 18 unsorted = true; 19 } 20 i += 2; 21 } 22 return unsorted; 23 } 24 25 private static void swap(int[] array, int index1, int index2) { 26 int temp = array[index1]; 27 array[index1] = array[index2]; 28 array[index2] = temp; 29 }