[Algorithm] The odd subscript is an even number of odd or even subscript

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.