Skip to content

Commit ad3e5b1

Browse files
committed
DH
1 parent 8176bc3 commit ad3e5b1

File tree

1 file changed

+90
-6
lines changed

1 file changed

+90
-6
lines changed

src/com/gw/myalgo/sort/SortAlgo.java

Lines changed: 90 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,48 @@ public static void selectSort(int[] arr) {
5454
}
5555
}
5656

57+
/**
58+
* 2-way select sort
59+
* @param arr
60+
*/
61+
public static void selectSortUpdate(int[] arr) {
62+
if(null == arr || 1 >= arr.length){
63+
return;
64+
}
65+
66+
for(int i = 0; i <= arr.length/2 ; i++){
67+
int minIdx = i, maxIdx = i;
68+
for(int j = i + 1; j < arr.length - i; j++) {
69+
if(arr[minIdx] >= arr[j]) {
70+
minIdx = j;
71+
}
72+
73+
if(arr[maxIdx] <= arr[j]) {
74+
maxIdx = j;
75+
}
76+
}
77+
78+
if(minIdx != i) {
79+
int tmp = arr[i];
80+
arr[i] = arr[minIdx];
81+
arr[minIdx] = tmp;
82+
if(maxIdx == i){
83+
maxIdx = minIdx;
84+
}
85+
}
86+
87+
int n = arr.length -i -1;
88+
if(maxIdx != n) {
89+
int tmp = arr[n];
90+
arr[n] = arr[maxIdx];
91+
arr[maxIdx] = tmp;
92+
}
93+
94+
printArr(arr);
95+
}
96+
}
97+
98+
5799
/**
58100
* Insert sort
59101
* @param arr
@@ -78,20 +120,62 @@ public static void insertSort(int[] arr){
78120
}
79121
}
80122

123+
}
124+
81125

126+
/**
127+
* Shell sort
128+
* @param arr
129+
*/
130+
public static void shellSortMain(int[] arr){
131+
132+
if(null == arr || 1 >= arr.length){
133+
return;
134+
}
135+
136+
int segment = arr.length/2;
137+
while(segment >= 1){
138+
shellInsertSort(arr,segment);
139+
segment = segment/2;
140+
}
82141
}
83142

143+
public static void shellInsertSort(int[] arr, int dk){
144+
if(null == arr || 1 >= arr.length || 0 >= dk){
145+
return;
146+
}
84147

85-
public static void main(String[] args) {
86-
int[] sortedArr = new int[]{1,3,1,2,8,4,6,2};
87-
//bubbleSort(sortedArr);
88-
//selectSort(sortedArr);
89-
insertSort(sortedArr);
148+
for(int i=dk; i < arr.length; ++i) {
149+
if(arr[i] < arr[i -dk]) {
150+
int j = i -dk, x=arr[i];
151+
arr[i]=arr[j];
152+
while(j >= 0 && x < arr[j]){
153+
arr[j+dk] = arr[j];
154+
j -= dk;
155+
}
156+
arr[j+dk] = x;
157+
}
158+
}
159+
}
90160

161+
public static void printArr(int[] arr){
91162
StringBuilder sb = new StringBuilder();
92-
for(int value : sortedArr){
163+
for(int value : arr){
93164
sb.append(value + ",");
94165
}
95166
System.out.println(sb.substring(0, sb.length() - 1));
96167
}
168+
169+
public static void main(String[] args) {
170+
//5,7,9,10,2,32,4,4,3
171+
int[] sortedArr = new int[]{5,7,9,10,2,32,4,4,3};
172+
printArr(sortedArr);
173+
//bubbleSort(sortedArr);
174+
//selectSort(sortedArr);
175+
selectSortUpdate(sortedArr);
176+
//insertSort(sortedArr);
177+
//shellSortMain(sortedArr);
178+
179+
printArr(sortedArr);
180+
}
97181
}

0 commit comments

Comments
 (0)