@@ -118,14 +118,59 @@ private static <T> int partition(Comparator<T> comparator, T[] arr, int start, i
118118 return par_index ;
119119 }
120120
121+ /**
122+ * 归并排序
123+ *
124+ * @param arr
125+ * @param comparator
126+ * @param <T>
127+ */
121128 public static <T > void mergeSort (T [] arr , Comparator <T > comparator ) {
122- //TODO 完成归并排序
129+ Preconditions .checkNotNull (arr );
130+ Preconditions .checkNotNull (comparator );
131+ mergeSort (arr , comparator , 0 , arr .length - 1 );
132+ }
133+
134+ private static <T > void mergeSort (T [] arr , Comparator <T > comparator , int start , int end ) {
135+ if (start < end ) {
136+ int middle = (end + start ) / 2 ;
137+ mergeSort (arr , comparator , start , middle );
138+ mergeSort (arr , comparator , middle + 1 , end );
139+ merge (arr , start , middle , end , comparator );
140+ }
141+ }
142+
143+ private static <T > void merge (T [] arr , int start , int middle , int end , Comparator <T > comparator ) {
144+ int front_start = start ;
145+ int end_start = middle + 1 ;
146+ int cur_pos = 0 ;
147+ T [] helper = (T []) new Object [end - start + 1 ];
148+ while (front_start <= middle && end_start <= end ) {
149+ if (comparator .compare (arr [front_start ], arr [end_start ]) <= 0 ) {
150+ helper [cur_pos ++] = arr [front_start ++];
151+ } else {
152+ helper [cur_pos ++] = arr [end_start ++];
153+ }
154+ }
155+
156+ while (front_start <= middle ) {
157+ helper [cur_pos ++] = arr [front_start ++];
158+ }
159+
160+ while (end_start <= end ) {
161+ helper [cur_pos ++] = arr [end_start ++];
162+ }
163+ System .arraycopy (helper , 0 , arr , start , helper .length );
123164 }
124165
125166 public static <T > void countSort (T [] arr , Comparator <T > comparator ) {
126167 //TODO 完成计数排序
127168 }
128169
170+ public static <T > void radixSort (T [] arr , Comparator <T > comparator ) {
171+
172+ }
173+
129174 public static <T > T [] leftRotate (T [] raw_array , int start , int end , int rot_index ) {
130175 Preconditions .checkNotNull (raw_array );
131176 Preconditions .checkPositionIndexes (start , end , raw_array .length );
@@ -154,9 +199,7 @@ public static <T extends Comparable<T>> T[] smallestK(T[] arr) {
154199 * @return
155200 */
156201 public static int [] bitMapSort (int [] un_sort_list ) {
157- if (null == un_sort_list ) {
158- throw new NullPointerException ("un_sort_list" );
159- }
202+ Preconditions .checkNotNull (un_sort_list );
160203 BitSet bit_set = new BitSet (un_sort_list .length / 8 );
161204 for (int x : un_sort_list ) {
162205 if (x < 0 ) {
0 commit comments