MergeSort(归并排序)
1 package algorithm.study.demo2; 2 3 4 /** 5 * This class implement MergeSort 6 * 7 * @author ygh 2017年2月23日 8 */ 9 public class MergeSort { 10 11 /** 12 * Arithmetic thoughts: If we want to sort a array elements,we can sort their left,then sort 13 * their right. In the left array, we can use same thought separate the left array to halt then 14 * sort them..... At last,it will change into tow number compare,then merge 15 * 16 * @param arr The array need to sort 17 * @param A temporary array to store elements that have sorted,its length is right-left 18 * 19 * @param left The left index of elements you want to sort in this array 20 * @param right The right index of elements you want to sort in this array 21 */ 22 public static void mergeSort(int[] sortedArr, int[] tmpArr, int left, int right) { 23 if (left < right) { 24 int mid = (left + right) / 2; 25 mergeSort(sortedArr, tmpArr, left, mid); 26 mergeSort(sortedArr, tmpArr, mid + 1, right); 27 merge(sortedArr, tmpArr, left, mid, right); 28 copy(sortedArr, tmpArr, left, right); 29 } 30 } 31 32 /** 33 * Copy elements from temporary array to sorted array. The index range is from left to rigth 34 * 35 * @param haltSortedArr The array need to sort 36 * @param tmpArr The temporary array 37 * @param left The left index 38 * @param right The right index 39 */ 40 private static void copy(int[] haltSortedArr, int[] tmpArr, int left, int right) { 41 for (int i = left; i <= right; i++) { 42 haltSortedArr[i] = tmpArr[i]; 43 } 44 } 45 46 /** 47 * This method is to merge elements from haltSortedArr.now the haltSortedArr has became sorted 48 * half by half.The elements' index from left to mid is sorted,and the elements' index from mid 49 * to right is sorted.So we just need to merge it to get all order array 50 * 51 * @param haltSortedArr The array has became sorted half by half 52 * @param tmpArr A temporary array to store elements order. 53 * @param left The left index of elements you want to sort in this array 54 * @param mid The order element separator index 55 * @param right The right index of elements you want to sort in this array 56 */ 57 private static void merge(int[] haltSortedArr, int[] tmpArr, int left, int mid, int right) { 58 int i = left; 59 int j = mid + 1; 60 int d = left; 61 while (i <= mid && j <= right) { 62 if (haltSortedArr[i] <= haltSortedArr[j]) { 63 tmpArr[d++] = haltSortedArr[i++]; 64 } else { 65 tmpArr[d++] = haltSortedArr[j++]; 66 } 67 } 68 69 if (i > mid) {// If i more mid,indicate some elements have not be put in temporary array in 70 // array right 71 while (j <= right) { 72 tmpArr[d++] = haltSortedArr[j++]; 73 } 74 } else {// If i less mid,indicate some elements have not be put in temporary array in array 75 // left 76 while (i <= mid) { 77 tmpArr[d++] = haltSortedArr[i++]; 78 } 79 } 80 } 81 82 }
quickSort(快速排序):
1 package algorithm.study.demo2; 2 3 /** 4 * This is quick sort implement 5 * 6 * @author ygh 2017年2月27日 7 */ 8 public class QuickSort { 9 10 /** 11 * Quick sort 12 * 13 * @param arr The array need to sort 14 * @param start The element sorted start index 15 * @param end The element sorted end index 16 */ 17 public static void quickSort(int arr[], int start, int end) { 18 if (start < end) { 19 int mid = partition(arr, start, end); 20 quickSort(arr, start, mid - 1); 21 quickSort(arr, mid + 1, end); 22 } 23 } 24 25 /** 26 * Get mid index and make the array left element less arr[mid] and right element more arr[mid] 27 * 28 * @param arr 29 * @param start 30 * @param end 31 * @return 32 */ 33 private static int partition(int[] arr, int start, int end) { 34 int value = arr[start]; 35 int i = start, j = end; 36 while (i < j) { 37 while (i < j && arr[j] >= value) { 38 j--; 39 } 40 arr[i] = arr[j]; 41 while (i < j && arr[i] <= value) { 42 i++; 43 } 44 arr[j] = arr[i]; 45 46 } 47 arr[i] = value; 48 return i; 49 } 50 51 }
shellSort(希尔排序):
1 package algorithm.study.demo2; 2 3 4 5 /** 6 * 7 * This class is to implement shell sort 8 * @author ygh 9 * 2017年2月27日 10 */ 11 public class ShellSort { 12 13 /** 14 * Shell sort 15 * @param arr The array need to sort 16 * @param gaps The gaps set in it 17 */ 18 public static void shellSort(int[] arr, int[] gaps) { 19 for (int i = 0; i < gaps.length; i++) { 20 shellInsert(arr, gaps[i]); 21 } 22 } 23 24 /** 25 * Insert sort for array by gap 26 * @param arr The sorted array 27 * @param gap The gap 28 */ 29 private static void shellInsert(int[] arr, int gap) { 30 int i, j, tmp; 31 for (i = gap; i < arr.length; i++) { 32 if (arr[i] < arr[i - gap]) { 33 tmp = arr[i]; 34 for (j = i - gap; j >= 0 && tmp < arr[j]; j = j - gap) { 35 arr[j + gap] = arr[j]; 36 } 37 arr[j + gap] = tmp; 38 } 39 } 40 } 41 42 }
测试方法的执行时间的工具类:
1 package algorithm.study.utils; 2 3 import java.lang.reflect.Method; 4 5 /** 6 * This class is getting a method execute time and provide some other functions. 7 * 8 * @author ygh 2017年2月24日 9 */ 10 public class MethodExecuteTimeUtils { 11 12 /** 13 * Get a method execute time using millisecond and cancel method's print return result and 14 * execute time. 15 * 16 * @param bean The method is in this bean 17 * @param params The parameter the method execute need 18 * @param methodName The name of the method 19 * @param types The parameter type of the method 20 * @return The execute time of this method 21 * @throws Exception If <code>getMethod</code> or <code>invoke</code> fail. 22 */ 23 public static long getMethodExecuteTime(Object bean, Object[] params, String methodName, Class<?>[] types) 24 throws Exception { 25 return getMethodExecuteTime(bean, params, methodName, types, false, false); 26 } 27 28 /** 29 * Get a method execute time using millisecond and cancel print method's return result. 30 * 31 * @param bean The method is in this bean 32 * @param params The parameter the method execute need 33 * @param methodName The name of the method 34 * @param types The parameter type of the method 35 * @param isPrintExecutetime Whether print the execute time in console, true is print false not 36 * @param isViewMehtodResult Whether print the return result in console, true is print false not 37 * @return The execute time of this method 38 * @throws Exception If <code>getMethod</code> or <code>invoke</code> fail. 39 */ 40 public static long getMethodExecuteTime(Object bean, Object[] params, String methodName, 41 Class<?>[] types, boolean isPrintExecutetime) throws Exception { 42 return getMethodExecuteTime(bean, params, methodName, types, isPrintExecutetime, false); 43 } 44 45 /** 46 * Get a method execute time using millisecond and add some other service. 47 * 48 * @param bean The method is in this bean 49 * @param params The parameter the method execute need 50 * @param methodName The name of the method 51 * @param types The parameter type of the method 52 * @param isPrintExecutetime Whether print the execute time in console, true is print false not 53 * @param isViewMehtodResult Whether print the return result in console, true is print false not 54 * @return The execute time of this method 55 * @throws Exception If <code>getMethod</code> or <code>invoke</code> fail. 56 */ 57 public static long getMethodExecuteTime(Object bean, Object[] params, String methodName, 58 Class<?>[] types, boolean isPrintExecutetime, boolean isViewMehtodResult) throws Exception { 59 Class<?> clazz; 60 long executeTime = -1L; 61 boolean isAccessiable = false; 62 Method method = null; 63 //determine bean is a instance or a Class<?> 64 if (bean instanceof Class<?>) { 65 clazz = (Class<?>) bean; 66 } else { 67 clazz = bean.getClass(); 68 } 69 try { 70 if (types == null) { 71 method = clazz.getDeclaredMethod(methodName); 72 } else { 73 method = clazz.getDeclaredMethod(methodName, types); 74 } 75 isAccessiable = method.isAccessible(); 76 if (!isAccessiable) { 77 method.setAccessible(true); 78 } 79 80 if (isViewMehtodResult) { 81 executeTime = getReturnMethodExecuteTime(bean, params, method); 82 } else { 83 executeTime = getMethodExecuteTime(bean, params, method); 84 } 85 method.setAccessible(isAccessiable); 86 if (isPrintExecutetime) { 87 printExecute(clazz, methodName, executeTime); 88 } 89 } catch (Exception e) { 90 throw new Exception("excute method fail"); 91 } 92 return executeTime; 93 } 94 95 /** 96 * Get a method execute time, use millisecond. We don't think the method whether has a return 97 * result 98 * 99 * @param bean The method is in this bean 100 * @param params The parameters the method execute need 101 * @param method The Method entity 102 * @return The millisecond the method execute spend 103 * @throws Exception If the method invoke fail 104 */ 105 private static long getMethodExecuteTime(Object bean, Object[] params, Method method) throws Exception { 106 long startTime = System.currentTimeMillis(); 107 method.invoke(bean, params); 108 long endTime = System.currentTimeMillis(); 109 return endTime - startTime; 110 } 111 112 /** 113 * Get a method execute time, use millisecond. The method must has a return result will input 114 * the return result in console ,If the method has not return result, please call 115 * <code>getMethodExecuteTime</code> method. 116 * 117 * @param bean The method is in this bean 118 * @param params The parameters the method execute need 119 * @param method The Method entity 120 * @return The millisecond the method execute spend 121 * @throws Exception If the method invoke fail 122 */ 123 private static long getReturnMethodExecuteTime(Object bean, Object[] params, Method method) 124 throws Exception { 125 long startTime = System.currentTimeMillis(); 126 Object result = (Object) method.invoke(bean, params); 127 long endTime = System.currentTimeMillis(); 128 if (result != null) { 129 System.out.println("result input:" + result.toString()); 130 } else { 131 System.out.println("Warning:" + bean.getClass().getName() + "." + method.getName() 132 + "has not return " + "result,please setting the isViewMehtodResult as false"); 133 } 134 return endTime - startTime; 135 } 136 137 /** 138 * Print the execute time of method 139 * 140 * @param methodName The name of the method 141 * @param time The execute of the method 142 */ 143 public static void printExecute(Class<?> clazz, String methodName, long time) { 144 System.out.println(clazz.getName() + "." + methodName + " execute time: " + time); 145 } 146 }
构造随机数组的工具类:
1 package algorithm.study.utils; 2 3 import java.util.Arrays; 4 5 /** 6 * A tool prepare for Array,it convenient to create 7 * a random array for sort and print them 8 * @author ygh 9 * 2017年2月27日 10 */ 11 public class ArraysTools { 12 13 /** 14 * Print a int[] into console 15 * @param arr The array need to print 16 */ 17 public static void toStringIntArray(int[] arr){ 18 System.out.println(Arrays.toString(arr)); 19 } 20 21 /** 22 * Get a random array by size and max value 23 * @param size The size the new array you want to create 24 * @param maxValue The max value in the array; 25 * @return A randow array 26 */ 27 public static int[] getRandomArray(int size,int maxValue){ 28 int []arr = new int[size]; 29 for(int i=0;i<size;i++){ 30 arr[i]=getIntRandomValue(maxValue); 31 } 32 return arr; 33 } 34 35 /** 36 * Get a random that less than max value 37 * @param maxValue The max value you get the random number 38 * @return A random number less than max value 39 */ 40 public static int getIntRandomValue(int maxValue){ 41 return (int) (Math.random()*maxValue); 42 } 43 44 }
测试排序的方法:
1 package algorithm.study.demo2; 2 3 import java.util.Arrays; 4 5 import org.junit.Test; 6 7 import algorithm.study.utils.ArraysTools; 8 import algorithm.study.utils.MethodExecuteTimeUtils; 9 10 public class SortMethodTest { 11 12 13 @Test 14 public void fun1() throws Exception{ 15 int maxValue=999999; 16 int[] sizes = getSize(1,7); 17 for(int i=0;i<sizes.length;i++){ 18 System.out.println("The size of array sorted is:"+sizes[i] 19 +" The max value is permited is:"+maxValue); 20 testSort(sizes[i],maxValue); 21 System.out.println("==============================================="); 22 } 23 } 24 25 public void testSort(int size,int maxValue) throws Exception{ 26 int[] arr1 = ArraysTools.getRandomArray(size, maxValue); 27 int[] arr2 = Arrays.copyOf(arr1, size); 28 int[] arr3 = Arrays.copyOf(arr1, size); 29 int[] arr4 = Arrays.copyOf(arr1, size); 30 testJavaSort(arr1); 31 testMergeSort(arr2); 32 testQuickSort(arr3); 33 if(size<999999){ 34 testShellSort(arr4); 35 }else{ 36 System.out.println("the size is very big,shell sort take to long time,so give it up"); 37 } 38 // ArraysTools.toStringIntArray(arr1); 39 // ArraysTools.toStringIntArray(arr2); 40 // ArraysTools.toStringIntArray(arr3); 41 // ArraysTools.toStringIntArray(arr4); 42 } 43 44 45 46 /** 47 * Test merge sort 48 * @param arr The array sorted 49 * @throws Exception If method execute failing 50 */ 51 public void testMergeSort(int[] arr) throws Exception{ 52 MergeSort bean = new MergeSort(); 53 Class<?>[] types = {int[].class,int[].class,int.class,int.class}; 54 String methodName = "mergeSort"; 55 int[] tmp = new int[arr.length]; 56 Object[] params={arr,tmp,0,arr.length-1}; 57 MethodExecuteTimeUtils.getMethodExecuteTime(bean, params, methodName, types, true); 58 } 59 60 /** 61 * Test quick sort 62 * @param arr The array sorted 63 * @throws Exception If method execute failing 64 */ 65 public void testQuickSort(int[] arr) throws Exception{ 66 QuickSort bean = new QuickSort(); 67 Class<?>[] types = {int[].class,int.class,int.class}; 68 String methodName = "quickSort"; 69 Object[] params={arr,0,arr.length-1}; 70 MethodExecuteTimeUtils.getMethodExecuteTime(bean, params, methodName, types, true); 71 } 72 73 /** 74 * Test shell sort 75 * @param arr The array sorted 76 * @throws Exception If method execute failing 77 */ 78 public void testShellSort(int[] arr) throws Exception{ 79 ShellSort bean = new ShellSort(); 80 Class<?>[] types = {int[].class,int[].class}; 81 String methodName = "shellSort"; 82 int[] gaps = getGaps(arr.length); 83 Object[] params={arr,gaps}; 84 MethodExecuteTimeUtils.getMethodExecuteTime(bean, params, methodName, types, true); 85 } 86 87 /** 88 * 89 * This is a method to test how long time the javaself sort method spend on 90 * @param arr The array need to sort 91 * @throws Exception If method execute failing 92 */ 93 public void testJavaSort(int[] arr) throws Exception{ 94 Class<?>[] types = {int[].class}; 95 String methodName = "sort"; 96 Object[] params = {arr}; 97 MethodExecuteTimeUtils.getMethodExecuteTime(Arrays.class, params, methodName, types,true); 98 } 99 100 101 /** 102 * Get gaps for shell sort 103 * @param size 104 * @return 105 */ 106 private int[] getGaps(int size){ 107 int[] gaps; 108 if(size>1000){ 109 gaps = new int[15]; 110 for(int i=1;i<=15;i++){ 111 gaps[i-1]=i; 112 } 113 }else{ 114 gaps = new int[5]; 115 for(int i=1;i<=5;i++){ 116 gaps[i-1]=i; 117 } 118 } 119 return gaps; 120 } 121 122 /** 123 * get array like [9, 99, 999, 9999, 99999, 999999, 9999999] 124 * @param start the first number is how many "9",the value of it must more or equal 0 125 * @param length The length of array 126 * @return A Integer array 127 */ 128 private int[] getSize(int start,int length){ 129 int[] arr = new int[length]; 130 int tmp=0; 131 for(int i=0;i<length+start-1;i++){ 132 tmp= (tmp)*10+9; 133 if(i>=start-1){ 134 arr[i-start+1] = tmp; 135 } 136 } 137 return arr; 138 } 139 140 141 }
测试结果:使用毫秒值:
The size of array sorted is:9 The max value is permited is:999999
java.util.Arrays.sort execute time: 0
algorithm.study.demo2.MergeSort.mergeSort execute time: 0
algorithm.study.demo2.QuickSort.quickSort execute time: 0
algorithm.study.demo2.ShellSort.shellSort execute time: 0
===============================================
The size of array sorted is:99 The max value is permited is:999999
java.util.Arrays.sort execute time: 0
algorithm.study.demo2.MergeSort.mergeSort execute time: 0
algorithm.study.demo2.QuickSort.quickSort execute time: 0
algorithm.study.demo2.ShellSort.shellSort execute time: 0
===============================================
The size of array sorted is:999 The max value is permited is:999999
java.util.Arrays.sort execute time: 1
algorithm.study.demo2.MergeSort.mergeSort execute time: 4
algorithm.study.demo2.QuickSort.quickSort execute time: 1
algorithm.study.demo2.ShellSort.shellSort execute time: 9
===============================================
The size of array sorted is:9999 The max value is permited is:999999
java.util.Arrays.sort execute time: 8
algorithm.study.demo2.MergeSort.mergeSort execute time: 3
algorithm.study.demo2.QuickSort.quickSort execute time: 2
algorithm.study.demo2.ShellSort.shellSort execute time: 85
===============================================
The size of array sorted is:99999 The max value is permited is:999999
java.util.Arrays.sort execute time: 57
algorithm.study.demo2.MergeSort.mergeSort execute time: 21
algorithm.study.demo2.QuickSort.quickSort execute time: 19
algorithm.study.demo2.ShellSort.shellSort execute time: 6125
===============================================
The size of array sorted is:999999 The max value is permited is:999999
java.util.Arrays.sort execute time: 115
algorithm.study.demo2.MergeSort.mergeSort execute time: 201
algorithm.study.demo2.QuickSort.quickSort execute time: 191
the size is very big,shell sort take to long time,so give it up
===============================================
The size of array sorted is:9999999 The max value is permited is:999999
java.util.Arrays.sort execute time: 1313
algorithm.study.demo2.MergeSort.mergeSort execute time: 2405
algorithm.study.demo2.QuickSort.quickSort execute time: 2048
the size is very big,shell sort take to long time,so give it up
===============================================