Adjust the array to make the odd number element an odd number, and the even number is an even number.

Source: Internet
Author: User

This article is entitled Baidu Quality Department interview questions

2n number, half odd number, half even number, design a program to make the number on the odd digit is odd, the number on the even bit is even, and calculate the space complexity and time complexity of the program

 

Program ideology:

This article is similar to adjusting the array so that the odd number is located in the first half of the array, and the even number is located in the second half of the array.

Set two pointers. One is initialized to ou = 0, and the other is initialized to ji = 1. If arr [ou] is an even number, ou + = 2. If arr [ji] is an odd number, ji + = 2;

If ou <len & ji <len, then it is judged that if the even number is an odd number and the odd number is an even number, the element is exchanged.

 

Public class jiou {public static void main (String [] args) {int [] arr = {0, 1, 3, 2, 2, 4, 4, 5, 5, 5, 7 }; reorder (arr); for (int I = 0; I <arr. length; I ++) {System. out. print (arr [I] + ",") ;}} public static void reorder (int [] arr) {if (arr = null) {System. out. println ("the array is null"); return;} int len = arr. length; int ou = 0; int ji = 1; while (ou <len & ji <len) {if (arr [ou] % 2 = 0) {ou = ou + 2;} if (arr [ji] % 2 = 1) {ji = ji + 2;} if (ou <len & ji <len) {// The purpose of this condition is to first determine whether the array subscript is out of bounds. If this condition is not added, the program may have an array subscript out-of-bounds error if (arr [ou] % 2 = 1 & arr [ji] % 2 = 0) {int temp = arr [ou]; arr [ou] = arr [ji]; arr [ji] = temp ;}}}}}

 

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.