从前往后找所要交换的两个数
void ReOrder(int* arr, int size) { if (arr == NULL || size <= 1)return; int i = 0,j = 0; while (i < size&&j < size){ while (i < size && ((arr[i] & 0x01) == 1)){//找偶数 ++i; } while (j < size && ((arr[j] & 0x01) == 0)){//找奇数 ++j; } if (i < size&&j < size){ if (i < j)//保证所找到的奇数在偶数的后面才进行交换 swap(arr[i], arr[j]); else//否则继续找下一个奇数 ++j; } } }
扩展性代码
只需要根据不同的需求实现solution()方法即可,_ReorderOddEven()函数可以被复用
//奇数放到偶数前面 bool solution(int n) { if ((n & 0x01) == 0)//n是偶数 return false; else return true; } //负数在非负数前面 bool solution2(int n) { if (n < 0) return true; else return false; } //能被3整除的在前面,不能被3整除的数在后面 bool solution3(int n) { if (n % 3 == 0) return true; else return false; } void _ReorderOddEven(int* arr, int size, bool(*Fun)(int)) { int* start = arr; int* end = start + size - 1; while (start < end){ while (start < end && Fun(*start)){ ++start; } while (start < end && !Fun(*end)){ --end; } if (start < end){ swap(*start, *end); ++start, --end; } } } void ReorderOddEven(int* arr, int size) { if (arr == NULL || size <= 1)return; bool(*fun)(int); fun = &solution; _ReorderOddEven(arr, size,fun); } void ReorderOddEven2(int* arr, int size) { if (arr == NULL || size <= 1)return; bool(*fun)(int); fun = &solution2; _ReorderOddEven(arr, size, fun); } void ReorderOddEven3(int* arr, int size) { if (arr == NULL || size <= 1)return; bool(*fun)(int); fun = &solution3; _ReorderOddEven(arr, size, fun); } int main() { /*int arr[] = { 1, 2, 3, 4, 5, 6, 20, 7, 19, 99, 100, 101 }; ReorderOddEven(arr, sizeof(arr) / sizeof(arr[0])); for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i){ cout << arr[i] << " "; }*/ /*int arr2[] = { -1, -5, 3, 7, 29, -4, 0, 98, -5 }; ReorderOddEven2(arr2, sizeof(arr2) / sizeof(arr2[0])); for (int i = 0; i < sizeof(arr2) / sizeof(arr2[0]); ++i){ cout << arr2[i] << " "; }*/ int arr3[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; ReorderOddEven3(arr3, sizeof(arr3) / sizeof(arr3[0])); for (int i = 0; i < sizeof(arr3) / sizeof(arr3[0]); ++i){ cout << arr3[i] << " "; } system("pause"); }
《完》
本文出自 “零蛋蛋” 博客,谢绝转载!
原文地址:http://lingdandan.blog.51cto.com/10697032/1908494