learning target:
Goal: proficiently use the knowledge learned in Java
Subject content:
The content of this article: Implemented in Java: Sorting Arrays by Parity
Article Directory
Title description:
Given an array of non-negative integers A, return an array in which all even elements of A are followed by all odd elements.
You can return any array that meets this condition as the answer.
Example:
Input: [3,1,2,4]
Output: [
2,4,3,1] Output [4,2,3,1], [2,4,1,3] and [4,2,1, 3] Will also be accepted.
Realize the idea:
This question is a disguised test of the sorting algorithm. You only need to change the conditions of the sorting algorithm. I will give you an idea of a quick sorting algorithm here.
Implementation code:
public class Practice_02 {
public static void main(String[] args) {
int[] A={
1,2,3,4,5,6};
System.out.println(Arrays.toString(sortArrayByParity(A)));
}
public static int[] sortArrayByParity(int[] A) {
int left = 0;
int right = A.length - 1;
while (left < right) {
while ((left < right) && (A[right] % 2 != 0)) {
right--;
}
while ((left < right) && (A[left] % 2 == 0)) {
left++;
}
int temp = A[left];
A[left] = A[right];
A[right] = temp;
right--;
left++;
}
return A;
}
}
operation result:
[6, 2, 4, 3, 5, 1]