分为两部分的问题,最好只用两个指针。
譬如此题:就可以一个指针从头往后扫,而另一个指针从后往前扫,保证第一个指针永远指向奇数,最后一个指针永远指向偶数,然后两者交换,直至最终两个指针相等,即扫描完了所有的元素。
代码如下所示:
1 //调整数组顺序使奇数位于偶数前面 2 #include<iostream> 3 using namespace std; 4 void function1(int* number, unsigned int length) 5 { 6 int p1 = 0; 7 int p2 = length - 1; 8 while (p1<p2) 9 { 10 while (p1 < p2 && (number[p1] & 0x1) != 0)//p1指向的不是偶数,p1++ 11 ++p1; 12 while (p1 < p2 && (number[p2] & 0x1) != 1)//p2指向的不是奇数,P2--; 13 --p2; 14 if (p1 < p2)//交换两个的值,注意:交换后的下一轮必然两个指针都会向中间靠拢 15 { 16 int temp = number[p1]; 17 number[p1] = number[p2]; 18 number[p2] = temp; 19 } 20 } 21 } 22 void print16(int* number, unsigned int length)//打印函数 23 { 24 for (int i = 0; i < length; ++i) 25 cout << number[i] << " "; 26 cout << endl; 27 } 28 int main16() 29 { 30 int A[7] = { 1, 2, 3, 4, 5, 6, 7 }; 31 function1(A, 7); 32 print16(A, 7); 33 system("pause"); 34 return 0; 35 }
代码的鲁棒性:
1 #include<iostream> 2 using namespace std; 3 void print16(int* number, unsigned int length) 4 { 5 for (int i = 0; i < length; ++i) 6 cout << number[i] << " "; 7 cout << endl; 8 } 9 //代码的可重用性 10 void Reorder(int *pData, unsigned int length, bool(*func)(int)) 11 { 12 int *pbegin = pData; 13 int *pend = pData + length - 1; 14 while (pbegin < pend) 15 { 16 while (pbegin < pend&&!func(*pbegin)) 17 ++pbegin; 18 while (pbegin < pend&&func(*pend)) 19 --pend; 20 if (pbegin < pend){ 21 int temp = *pbegin; 22 *pbegin = *pend; 23 *pend = temp; 24 } 25 } 26 } 27 bool isEven(int n) 28 { 29 return (n & 1) == 0; 30 } 31 void ReorderOddEven(int *pData, unsigned int length) 32 { 33 Reorder(pData, length, isEven); 34 } 35 int main16() 36 { 37 int A[7] = { 1, 2, 3, 4, 5, 6, 7 }; 38 //function1(A, 7); 39 //print16(A, 7); 40 ReorderOddEven(A, 7); 41 print16(A, 7); 42 system("pause"); 43 return 0; 44 }
时间: 2024-10-13 23:21:52