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