二路归并排序,利用递归,时间复杂度o(nlgn)
public class MergeSort { public void mergeSort(int[]data, int left, int right) { if(left >= right) return; int mid = (left + right)/2; mergeSort(data, left, mid); mergeSort(data, mid+1, right); merge(data, left, mid, right); } public void merge(int[]data, int left, int mid, int right) { int[] temp = new int[data.length];//临时数组 int index = left;//临时数组的下标 int tmp = left;//记录data的左下标 int center = mid + 1; while(left <= mid && center <= right) { if(data[left] < data[center]) { temp[index++] = data[left++]; } else { temp[index++] = data[center++]; } } while(left <= mid) { temp[index++] = data[left++]; } while(center <= right) { temp[index++] = data[center++]; } while(tmp <= right)//将临时数组拷贝到原数组 { data[tmp] = temp[tmp++]; } } public static void main(String[] args) { int[] data = {3, 1, 4, 5, 15, 2, 8}; MergeSort ms = new MergeSort(); ms.mergeSort(data, 0, 6); for (int i : data) { System.out.print(i+"\t"); } } }