@@ -54,6 +54,48 @@ public static void selectSort(int[] arr) {
54
54
}
55
55
}
56
56
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
+
57
99
/**
58
100
* Insert sort
59
101
* @param arr
@@ -78,20 +120,62 @@ public static void insertSort(int[] arr){
78
120
}
79
121
}
80
122
123
+ }
124
+
81
125
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
+ }
82
141
}
83
142
143
+ public static void shellInsertSort (int [] arr , int dk ){
144
+ if (null == arr || 1 >= arr .length || 0 >= dk ){
145
+ return ;
146
+ }
84
147
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
+ }
90
160
161
+ public static void printArr (int [] arr ){
91
162
StringBuilder sb = new StringBuilder ();
92
- for (int value : sortedArr ){
163
+ for (int value : arr ){
93
164
sb .append (value + "," );
94
165
}
95
166
System .out .println (sb .substring (0 , sb .length () - 1 ));
96
167
}
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
+ }
97
181
}
0 commit comments