请完成sort的代码实现(
void sort(int[]a) { … }
例如: 当输入a = {8,4,1,6,7,4,9,6,4},
a = {1,7,9,8,4,6,4,6,4}为一种满足条件的排序结果。
快慢指针同时从一侧出发,找到第一个偶数时,慢指针停下来,快指针寻找下一个奇数,找到就交换,然后快慢指针+1继续。 int[] sort(int[] a){ int len = a.length; int pre = 0; int pos = 0; boolean flag = true; for(; pos<len; pos++) { if(flag && a[pos] % 2 == 0) { pre = pos; flag = false; } if((!flag) && a[pos] % 2 == 1) { int temp = a[pos]; a[pos] = a[pre]; a[pre] = temp; pre++; } } return a; }
//(1)设置begin, end两个指针,begin指向数组的偶数,end指向数组的奇数;
//(2)交换偶数和奇数,同时begin++,end--;
public void sort(int a[]) { int begin = 0, end = a.length - 1; while(begin < end) { if(a[begin] % 2 == 0 && a[end] % 2 == 1) { int temp = a[begin]; a[begin] = a[end]; a[end] = temp; } else if(a[begin] % 2 == 1) { begin++; } else if(a[end] % 2 == 0) { end--; } } for(int jj = 0; jj< a.length; jj++) { System.out.print(a[jj]); } }
import java.util.*; public class test17 { public static void main(String[] args) { int[] A = { 8, 4, 1, 6, 7, 4, 9, 6, 4 }; int slow = 0, fast = 0; while (fast < A.length) { if (A[fast] % 2 == 1) { int tmp; tmp = A[fast]; A[fast] = A[slow]; A[slow] = tmp; slow++; } fast++; } for (int i = 0; i < A.length; i++) { System.out.println(A[i]); } } }
public class SortArr { public static void main(String[] args) { int[] arr = {8,4,1,6,7,4,9,6,4}; sort(arr); System.out.println(Arrays.toString(arr)); } public static void sort(int[] arr) { int count = 0; for (int i = 0; i < arr.length; i++){ if(arr[i]%2!=0){ //奇数 if(i!=count){ swap(arr,i,count); } count++; } } } public static void swap(int[] arr,int i,int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
int jicount = 0; int temp; for (int i = 0; i < a.length; i++) { if (a[i] % 2 != 0) { jicount++; } } int n = jicount - 1, m = jicount; for (; n >= 0; n--) { while (a[m] % 2 == 0 && m < a.length) { m++; } if (a[n] % 2 == 0) { temp = a[n]; a[n] = a[m]; a[m] = temp; } }
void sort(int A[], int n) { int x; int i = 0; int j = n-1; while(i != j) { while( a[i]%2 == 1) i++; while (a[j]%2 == 0) j--; if(i < j) { x = a[i]; a[i] = a[j]; a[j] = x; } } }
void sort(int[] a){ Deque<Integer> dq = new ArrayDeque<>(); for(int i=0;i<a.length;i++) { if(a[i]%2 == 1) { dq.addFirst(a[i]); }else { dq.addLast(a[i]); } } System.out.println("a="+dq.toString()); }
static void sort(int[] a) { for (int i = 0; i < a.length - 1; i++) { for (int j = i + 1; j > 0; j--) { // if odd and former is even, then exchange if (a[j] % 2 == 1 && a[j - 1] % 2 == 0) { swap(a, j - 1, j); } else { break; } } } } // exchange place static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; }
void sort(int[] a){ int[] result = new int[a.length]; int index_front = 0; int index =0; for(int i = 0 ; i < a.length; i ++){ if(a[i] % 2 == 0){ result[index++] = a[i]; } else{ int temp = result[index_front]; result[index_front++] = a[i]; index ++; for(int i = index_front; i <index; i ++){ int temp_1 = a[i]; a[i] = temp; temp = temp_1; } } } for(int i = 0; i < a.length; i ++){ a[i] = result[i]; } }