forked from JiauZhang/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreorder_array.cpp
107 lines (95 loc) · 2.54 KB
/
reorder_array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* Copyright(c) 2019 Jiau Zhang
* For more information see <https://github.com/JiauZhang/algorithms>
*
* This repo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation
*
* It is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with THIS repo. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
using namespace std;
//#define DEBUG
#ifdef DEBUG
#define debug(numbers, length) print_numbers(numbers, length)
#else
#define debug(numbers, length)
#endif
void print_numbers(int numbers[], int length)
{
int len = 0;
while(len<length) {
cout << numbers[len] << ' ';
len++;
}
cout << endl;
#ifdef DEBUG
len = 0;
while(len<length) {
cout << (numbers[len])%2 << ' ';
len++;
}
cout << endl;
#endif
}
void reorder(int numbers[], int length)
{
if(!numbers || length<=0)
return;
int* head,* tail;
head = numbers;
tail = numbers+length-1;
bool odd = false, even = false;
//int & 0x01 会有问题,不能正确判断奇偶性
while(head<tail && head != tail) { //head!=tail用来防止全是奇数和全是偶数是指针超出范围
//if((*head)&0x01) { //如果是奇数指针就往尾方向走,偶数就停止
if((*head)%2) {
++head;
} else {
odd = true;
}
//if((*tail)&0x01 == 0) { //如果是偶数则往头方向走,奇数就停止
if((*tail)%2 == 0) {
--tail;
} else {
even = true;
}
if(odd && even) {
odd = false;
even = false;
int temp = *head;
*head = *tail;
*tail = temp;
head++;
tail--;
debug(numbers, 15);
}
}
}
int main(int argc, char** argv)
{
int numbers_test1[15] = {1, 21, 2, 3, 4, 5, 6, 7, 8, 9, 0, 13, 22, 22, 33};
debug(numbers_test1, 15);
reorder(numbers_test1, 15);
print_numbers(numbers_test1, 15);
int numbers_test2[5] = {1, 3, 5, 7, 9};
reorder(numbers_test2, 5);
print_numbers(numbers_test2, 5);
int numbers_test3[5] = {0, 2, 4, 6, 8};
reorder(numbers_test3, 5);
print_numbers(numbers_test3, 5);
int numbers_test4[10] = {0, 2, 4, 6, 8, 1, 3, 5, 7, 9};
reorder(numbers_test4, 10);
print_numbers(numbers_test4, 10);
int numbers_test5[10] = {1, 3, 5, 7, 9, 0, 2, 4, 6, 8};
reorder(numbers_test5, 10);
print_numbers(numbers_test5, 10);
return 0;
}