剑指Offer12 数组奇数调整至偶数前

 1 /*************************************************************************
 2     > File Name: 12_ReorderArray.c
 3     > Author: Juntaran
 4     > Mail: JuntaranMail@gmail.com
 5     > Created Time: 2016年08月30日 星期二 15时15分42秒
 6  ************************************************************************/
 7 
 8 #include <stdio.h>
 9 #include <stdlib.h>
10 
11 // 所有奇数放在偶数前面
12 void ReorderOddEven(int* nums, int length)
13 {
14     if (length <= 0)
15         return;
16     
17     int left  = 0;
18     int right = length - 1;
19     
20     while (left < right)
21     {
22         // 从左向右找第一个偶数
23         while (nums[left] % 2 != 0)
24             left ++;
25         
26         // 从右向左找第一个奇数
27         while (nums[right] %2 == 0)
28             right --;
29         
30         if (left < right)
31         {
32             int temp = nums[left];
33             nums[left]  = nums[right];
34             nums[right] = temp;
35         }
36     }
37 }
38 
39 void PrintNums(int* nums, int length)
40 {
41     for (int i = 0; i < length; ++i)
42         printf("%d ", nums[i]);
43     
44     printf("
");
45 }
46 
47 int main()
48 {
49     int nums[] = {1, 2, 3, 4, 5, 6};
50     int length = 6;
51     
52     PrintNums(nums, length);
53     ReorderOddEven(nums, length);
54     PrintNums(nums, length);
55     
56     return 0;
57 }
原文地址:https://www.cnblogs.com/Juntaran/p/5823149.html