标签:左右 compareto mergesort return rtb 数据 com ges ext
归并排序:升序排
private <T extends Comparable<? super T>> void mergeSortByAsc(T[] data, int low,int high) { T[] temp; /** 如果左右相等,则返回 */ if(low == high) return; /** 找到长度和中间的那个数*/ int size = high - low +1; int mid = (low + high)/2; temp = (T[])(new Comparable[size]); /** 对左边的数据进行排序*/ mergeSort(data, low, mid); /** 对右边的数据进行排序*/ mergeSort(data, mid + 1, high); /** copy 排序的数组*/ for(int i = 0;i < size; i++){ temp[i] = data[low + i]; } /** 合并两个排序的数组*/ int left = 0; int right = mid - low + 1; for(int i = 0; i < size; i++){ if(right <= high - low){ if(left <= mid - low){ if(temp[left].compareTo(temp[right]) > 0){ data[i + low] = temp[right ++ ]; }else{ data[i + low] = temp[left ++]; } }else{ data[i + low] = temp[right ++ ]; } }else{ data[i + low] = temp[left ++]; } } }
降序排:
private <T extends Comparable<? super T>> void mergeSortByDesc(T[] data, int low,int high) { T[] temp; /** 如果左右相等,则返回 */ if(low == high) return; /** 找到长度和中间的那个数*/ int size = high - low +1; int mid = (low + high)/2; temp = (T[])(new Comparable[size]); /** 对左边的数据进行排序*/ mergeSortByDesc(data, low, mid); /** 对右边的数据进行排序*/ mergeSortByDesc(data, mid + 1, high); /** copy 排序的数组*/ for(int i = 0;i < size; i++){ temp[i] = data[low + i]; } /** 合并两个排序的数组*/ int left = 0; int right = mid - low + 1; for(int i = 0; i < size; i++){ if(right <= high - low){ if(left <= mid - low){ if(temp[left].compareTo(temp[right]) < 0){ data[i + low] = temp[right ++ ]; }else{ data[i + low] = temp[left ++]; } }else{ data[i + low] = temp[right ++ ]; } }else{ data[i + low] = temp[left ++]; } } }
标签:左右 compareto mergesort return rtb 数据 com ges ext
原文地址:http://www.cnblogs.com/Gabby/p/6522989.html