【面试题14】调整数组顺序使奇数位于偶数前面

【题目描述】

输入一个整数数组,实现一个函数来调用该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。

【解决方案】

1. 只完成基本功能的解法,仅适用于初级程序员

方法:设置头尾两个指针,满足条件就交换,直到碰头为止。

我的代码实现,仅供参考:

 1         public static void AdjustArray(int[] arr)
 2         {
 3             if (arr == null || arr.Length < 1)
 4             {
 5                 return;
 6             }
 7 
 8             int start = 0;
 9             int end = arr.Length - 1;
10 
11             while (start < end)
12             {
13                 while ((start < end) && (arr[start] % 2 == 1))
14                 {
15                     start++;
16                 }
17 
18                 while ((start < end) && (arr[end] % 2 == 0))
19                 {
20                     end--;
21                 }
22 
23                 if (start < end)
24                 {
25                     Swap(arr, end, start);
26                 }
27             }
28         }
29 
30         public static void Swap(int[] arr, int indexA, int indexB)
31         {
32             int temp = arr[indexA];
33             arr[indexA] = arr[indexB];
34             arr[indexB] = temp;
35         }

2. 考虑可拓展性的解法,能秒杀Offer

在上述问题中,只是要求奇数偶数分开,如果正数负数分开呢?按照是否能被3整除分开呢?

所以,我可以把判断分类的条件抽离出来,单独形成一个判定条件的函数,哪怕以后改了需求,也只需找到对应函数修改即可。

我的代码实现,仅供参考:

 1         public static void AdjustArray(int[] arr)
 2         {
 3             if (arr == null || arr.Length < 1)
 4             {
 5                 return;
 6             }
 7 
 8             int start = 0;
 9             int end = arr.Length - 1;
10 
11             while (start < end)
12             {
13                 while ((start < end) && !IsValid(arr[start]))
14                 {
15                     start++;
16                 }
17 
18                 while ((start < end) && IsValid(arr[end]))
19                 {
20                     end--;
21                 }
22 
23                 if (start < end)
24                 {
25                     Swap(arr, end, start);
26                 }
27             }
28         }
29 
30         public static bool IsValid(int num)
31         {
32             return num % 2 == 0;
33         }
34 
35         public static void Swap(int[] arr, int indexA, int indexB)
36         {
37             int temp = arr[indexA];
38             arr[indexA] = arr[indexB];
39             arr[indexB] = temp;
40         }
原文地址:https://www.cnblogs.com/HuoAA/p/4803083.html