[Algorithm Summary-array] Move the array-> left odd right even

Source: Internet
Author: User

If an integer array is given, the array must be operated in the form of an odd number on the left and an even number on the right.

Idea: The Division Method of quick sorting was originally divided by comparison with a certain value. Change this algorithm policy to be divided based on the parity of each number.

Implementation 1:

/** Move the array, the even number to the right, and the odd number to the left * Method 1: Use a method similar to quick sorting * scan with a pointer, when an odd number is encountered, it is exchanged with the next element of the moved part (another pointer stores the right boundary of an odd number that has been moved) * scan once to complete, time complexity O (N ), space O (1) */void partition (INT arr [], int N) {int I =-1, end = n-1; For (Int J = start; j <= end; j ++) {If (ARR [J] % 2 = 1) {I ++; if (I! = J) {int temp = arr [I]; arr [I] = arr [J]; arr [J] = temp ;}}}}

Implementation 2:

Int partition (INT arr [], int N) {int I = 0; Int J = n-1; while (I <j) {While (I <J & (ARR [I] % 2 = 1) I ++; while (I <J & (ARR [J] % 2 = 0) j --; if (I <j) {swap (& arr [I], & amp; arr [J]) ;}} return I; // returns the index starting with an even number. You can leave it blank}

For PHP, the implementation method can be simpler. Directly scan the array. If it is an odd number, it is placed into the left array. Otherwise, right is placed into the right array and the result of array_merge is returned.

/** Method 2: For PHP, the processing method can be simpler. * scan the array directly. If it is an odd number, add the value to left_array. Otherwise, add the value to right_array. returns the merge result. * disadvantage: extra space required for O (n) */function partition ($ ARR) {$ left = array (); $ right = array (); for ($ J = 0; $ j <count ($ ARR); $ J ++) {if ($ arr [$ J] % 2 = 1) {$ left [] = $ arr [$ J];} else {$ right [] = $ arr [$ J] ;}} return array_merge ($ left, $ right );}

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.