Adjust the array order so that the odd digits are preceded by even numbers

Source: Internet
Author: User

enter an array of integers to implement a function to adjust the order of the numbers in the array so that all the odd digits are in the first half of the array. The entire number of even digits is located in the second half of the array.

Code:

/* Adjust the array order so that the odd digits are in the even front by rowandjj2014/8/1*/#include <iostream> #include <stdlib.h>using namespace std;//efficient solution , but the relative order of the array elements that will be adjusted changes to void func (int *parr,int len) {if (PArr = = NULL | | Len <= 1) {return;} int low = 0,high = Len-1;while (Low < High) {while (Low < high && (Parr[low] & 0x1)! = 0) The//low pointer moves back until it encounters even {lo w++;} while (Low < high && (Parr[high] & 0x1) = = 0) The//high pointer moves forward until it encounters an odd {high--;} if (Low < high)//Assume that the low pointer is in front of the high pointer. Then swap the two pointers to the elements {int temp = Parr[low];p Arr[low] = Parr[high];p Arr[high] = temp;}}} Use auxiliary array void Func2 (int *parr,int len) {if (PArr = = NULL | | Len <= 1) {return;} int *temp = (int*) malloc (sizeof (int) *len), if (!temp) {exit (-1);} int i,j = 0;for (i = 0; i< len; i++)//First odd copy to auxiliary array before {if ((Parr[i] & 0x1)!=0) {temp[j++] = Parr[i];}} for (i = 0; i < len; i++)//Copy even to auxiliary array after {if ((Parr[i] & 0x1) = = 0) {temp[j++] = Parr[i];}} for (i = 0; i < len; i++)//overwrite original array {parr[i] = temp[i];} Free (temp);} int main () {int n;cin>>n;if (n <= 0) {return 0;} int *parr = (int*) malloc (sizeof (int) *n); if (!parr) {return 0;} for (int i = 0; i < n; i++) {cin>>* (parr+i);} Func2 (Parr,n); for (int j = 0; J < N; j + +) {if (j = = n-1) {cout<<* (parr+j) << "\ n";} else{cout<<* (parr+j) << "";}} Free (PARR); return 0;}


Adjust the array order so that the odd digits are preceded by even numbers

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.