Skip to content

Commit e782532

Browse files
committed
添加奇偶排序
1 parent 678efa6 commit e782532

3 files changed

Lines changed: 38 additions & 5 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
- 希尔排序
99
- 交换排序
1010
- 冒泡泡排序
11+
- 奇偶排序
1112
- 快速排序
1213
- 选择排序
1314
- 直接选择排序

src/org/algorithm/array/sort/client/SortClient.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
package org.algorithm.array.sort.client;
22

3-
import org.algorithm.array.sort.impl.ShellSort;
3+
import org.algorithm.array.sort.impl.OddEvenSort;
44
import org.algorithm.array.sort.interf.Sortable;
55
import org.utils.naga.containers.ArrayUtils;
66

77
public class SortClient {
88

99
public static void main(String[] args) {
1010
int[] array = {34, 23, 76, 56, 54, 12, 34, 65, 45, 9, 8, 7, 6, 5};
11-
// int[] array = {13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
12-
Sortable sortable = new ShellSort();
11+
// int[] array = {6, 5, 4, 3, 2, 1};
12+
Sortable sortable = new OddEvenSort();
1313
array = sortable.sort(array);
1414

1515
ArrayUtils.show(array);

src/org/algorithm/array/sort/impl/OddEvenSort.java

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package org.algorithm.array.sort.impl;
22

33
import org.algorithm.array.sort.interf.Sortable;
4+
import org.utils.naga.containers.ArrayUtils;
45

56
/**
67
* <p>
@@ -19,8 +20,39 @@ public class OddEvenSort implements Sortable {
1920

2021
@Override
2122
public int[] sort(int[] array) {
22-
// TODO Auto-generated method stub
23-
return null;
23+
if (array == null) {
24+
return null;
25+
}
26+
27+
core(array);
28+
29+
return array;
2430
}
2531

32+
private void core(int[] array) {
33+
int arrayLength = array.length;
34+
boolean oddSorted = false;
35+
boolean evenSorted = false;
36+
37+
while(!oddSorted || !evenSorted) {
38+
int base = 0;
39+
oddSorted = true;
40+
evenSorted = true;
41+
42+
for (int i = base; i < arrayLength - 1; i += 2) {
43+
if (array[i] > array[i + 1]) {
44+
ArrayUtils.swap(array, i, i + 1);
45+
oddSorted = false;
46+
}
47+
}
48+
49+
base = 1;
50+
for (int i = base; i < arrayLength - 1; i += 2) {
51+
if (array[i] > array[i + 1]) {
52+
ArrayUtils.swap(array, i, i + 1);
53+
evenSorted = false;
54+
}
55+
}
56+
}
57+
}
2658
}

0 commit comments

Comments
 (0)