Topic:
Given an array of length not less than 2 arr, implement a function to adjust arr, either to make all even subscript an even number, or to make all odd subscripts odd.
Requirements: The time complexity is O (N), the additional space complexity is O (1).
Program:
Public Static void Modify (int[] arr) {
if Null | | Arr.length < 2) {
return;
}
int even = 0;
int odd = 1;
int end = arr.length-1;
while (even <= end && odd <= end) {
PrintArray (arr);
if ((Arr[end] & 1) = = 0) {
Swap (arr, end, even);
even + = 2;
Else {
Swap (arr, end, odd);
Odd + = 2;
}
}
}
Public Static void swap (intint int index2) {
int tmp = arr[index1];
ARR[INDEX1] = Arr[index2];
ARR[INDEX2] = tmp;
}
Public Static void printArray (int[] arr) {
for (int i = 0; I! = Arr.length; i++) {
System.out.print (Arr[i] + "");
}
System.out.println ();
}
[Algorithm] The odd subscript is an even number of odd or even subscript