【數組】調整數組順序使奇數位於偶數前面


1. 輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得所有的奇數位於數組的前半部分,所有的偶數位於位於數組的后半部分。

 1 /**
 2  * 調整數組順序使奇數位於偶數前面
 3  * 
 4  * @author
 5  *
 6  */
 7 public class Solution {
 8 
 9     public static void order(int[] array) {
10 
11         if (null == array || array.length == 0 || array.length == 1) {
12             return;
13         }
14 
15         int start = 0; // 從頭開始向后移動的指針
16         int end = array.length - 1; // 從尾開始向前移動的指針
17 
18         while (start < end) {
19 
20             // 滿足前偶后奇進行交換
21             if ((array[start] & 1) == 0 && ((array[end] & 1) == 1)) {
22                 swap(array, start, end);
23             }
24 
25             if ((array[start] & 1) == 1) {
26                 start++;
27             }
28 
29             if ((array[end] & 1) == 0) {
30                 end--;
31             }
32 
33         }
34     }
35 
36     public static void swap(int[] array, int m, int n) {
37         int temp;
38         temp = array[m];
39         array[m] = array[n];
40         array[n] = temp;
41     }
42 
43     public static void main(String[] argss) {
44 
45         int[] array = { 1, 2, 3, 4, 5, 6, 7 };
46 
47         System.out.println("調整前:");
48         for (int i : array) {
49             System.out.print(i + " ");
50         }
51 
52         order(array);
53 
54         System.out.println("\n調整后:");
55         for (int i : array) {
56             System.out.print(i + " ");
57         }
58     }
59 }

 

調整前:
1 2 3 4 5 6 7 
調整后:
1 7 3 5 4 6 2 

 

2.輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得所有的奇數位於數組的前半部分,所有的偶數位於位於數組的后半部分,並保證奇數和奇數,偶數和偶數之間的相對位置不變。

 

 1 import java.util.List;
 2 
 3 public class Solution
 4 {
 5     public void reOrderArray(int[] array)
 6     {
 7         if (array.length == 0)
 8         {
 9             return;
10         }
11         
12         int temp = 0;
13         boolean flag;
14         
15         //類似插入排序,每次將奇數插入到所有偶數的前面
16         for (int i = 0; i < array.length; i++)
17         {
18             flag = true;
19             if ((array[i] & 1) == 1)
20             {
21                 for (int j = i; flag && j>0; j--)
22                 {
23                     if ((array[j - 1] & 1) == 0)
24                     {
25                         temp = array[j];
26                         array[j] = array[j - 1];
27                         array[j - 1] = temp;
28                     }else{
29                         flag = false;
30                     }
31                 }
32             }
33         }
34         
35     }
36 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM