给定一个存放整数的数组,请设计个函数,重新排列数组使得数组前面为奇数,后面全偶数,同时函数返回重排后第一个为偶数的元素在数组中的位置。
int mypar(int a[],int low,int high) { int key = a[low]; int sz = high; while (low < high) { while (low < high && a[high] % 2 == 0) { high--; } if (low < high) { a[low] = a[high]; low++; } while (low < high && a[low] % 2 == 1) { low++; } if (low < high) { a[high] = a[low]; high--; } } a[low] = key; if (key%2 == 0)//key是偶数 { return low; } //key是奇数 if (low < sz)//有偶数 { return low + 1;//中轴后一位是偶数 } return -1;//没有偶数 }
public class test2 { public static void main(String[] args) { int[] a={2,3,5,6,33,41,24,87,34,32,15,6}; for (int i:a ) { System.out.print(" "+i); } System.out.println(); System.out.println("第一个偶数的位置:"+fun(a)); for (int i:a ) { System.out.print(" "+i); } } public static int fun(int[] a){ int j=a.length-1; int i=0; int temp=a[i]; while(i<j){ while (i<j && a[i]%2!=0) i++; if(i==j) return i; else {temp=a[i];} while (i<j && a[j]%2==0) j--; if(i==j) return i; else { a[i]=a[j]; a[j]=temp; i++; } } return i; } }