调整数组顺序使奇数位于偶数前面

来源:互联网 发布:最好广告过滤软件 编辑:程序博客网 时间:2024/06/05 11:01
#include <iostream>using namespace std;inline bool IsOdd(int *a){return *a % 2 == 0;}void Sort(int a[], int len){if (a == NULL || len == 0)return;else{int *p1 = a, *p2 = a + len - 1;while (p2 > p1){while (!IsOdd(p1))++p1;while (IsOdd(p2))--p2;if (p2 > p1)swap(*p1, *p2);}}for (int i = 0; i != len; ++i)cout << a[i] << endl;}int main(){int a[] = { 0,1,2,3,4,5,6,7 };Sort(a, 8);system("pause");return 0;}
这是不稳定的排序,时间复杂度O(n),空间复杂度O(1)。稳定的排序今天一时没写出来,先挖空,改天更。讲道理,稳定排序的时间复杂度为O(n2).

0 0
原创粉丝点击