将一个数组分成奇数部分和偶数部分,并分别排好序 CVTE

给定一个数组,将奇数放到前面,偶数放到后面,各自排好序

(2016年3月12日晚上,CVTE笔试编程第一道题):

思路很简单:

(1)先将数组中的奇数和偶数分开(利用两个指针遍历一遍即可,同时统计好数组中奇数的个数);

(2)然后分别进行快速排序。

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<queue>
 4 using namespace std;
 5 void quick_sort(int *nums, int first, int last);
 6 int partion(int *nums, int first, int last);
 7 void sort(int *nums, int length)
 8 {
 9     int count1 = 0, count2 = 0;
10     int *first = nums;
11     int *last = nums + length - 1;
12     while (first < last)
13     {
14         while (*first % 2 == 1)
15         {
16             count1++; first++;
17         }
18         while (*last % 2 == 0)
19         {
20             count2++; last--;
21         }
22         if (first < last)//这个条件判断很是关键,防止一开始就归类好的情况下(前面都是奇数,后面都是偶数),二者越界交换
23         {
24             int temp = *first; *first = *last; *last = temp;
25             first++;
26             last--;
27             count1++;//二者交换完成后,也别忘记各自统计一次
28             count2++;
29         }
30     }
31     quick_sort(nums, 0, count1 - 1);
32     quick_sort(nums, count1, length - 1);
33 }
34 void quick_sort(int *nums, int first, int last)
35 {
36     if (first >= last)return;
37     int  mid = partion(nums, first, last);
38     quick_sort(nums, first, mid - 1);
39     quick_sort(nums, mid + 1, last);
40 }
41 int partion(int *nums, int first, int last)
42 {
43     int ptvor = nums[first];
44     while (first < last)
45     {
46         while (nums[last]>ptvor&&first < last)
47             last--;
48         nums[first] = nums[last];
49         while (nums[first] <= ptvor && first < last) first++;
50         nums[last] = nums[first];
51         swap(nums[first], nums[last]);//????2016年3月22日再看到,莫名其妙的一句是不是
52     }
53     nums[last] = ptvor;
54     return last;
55 }
56 
57 int main()
58 {
59     int nums[10] = { 3, 6, 2, 10, 9, 22, 1, 8, 13, 15 };
60     sort(nums, 10);
61     for (int i = 0; i < 10; i++)
62         cout << nums[i] << " ";
63     return 0;
64 }
手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
原文地址:https://www.cnblogs.com/chess/p/5270265.html