zoukankan      html  css  js  c++  java
  • 归并排序

    package test;
    
    public class MergeSort {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		int[] arr = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
    		System.out.println("排序前:");
    		printArr(arr);
    		sort(arr);
    		System.out.println("排序后:");
    		printArr(arr);
    	}
    
    	private static void sort(int[] arr) {
    		int[] tmp = new int[arr.length];
    		sort(arr, 0, arr.length - 1, tmp);
    
    	}
    
    	private static void sort(int[] arr, int left, int right, int[] tmp) {
    
    		if (left < right) {
    			int mid = (left + right) / 2;
    			sort(arr, left, mid, tmp);
    			sort(arr, mid + 1, right, tmp);
    			merge(arr, left, mid, right, tmp);
    		}
    	}
    
    	private static void merge(int[] arr, int left, int mid, int right, int[] tmp) {
    		int i = left;
    		int j = mid + 1;
    		int t = 0;
    
    		while (i <= mid && j <= right) {
    			if (arr[i] <= arr[j]) {
    				tmp[t++] = arr[i];
    				i++;
    			} else {
    				tmp[t++] = arr[j];
    				j++;
    			}
    
    		}
    		for (; i <= mid; i++) {
    			tmp[t++] = arr[i];
    
    		}
    		for (; j <= right; j++) {
    			tmp[t++] = arr[j];
    
    		}
    
    		// 将tmp前t个数据拷贝到arr的Left至right的位置中;
    		System.arraycopy(tmp, 0, arr, left, t);
    
    		printArr(arr);
    
    		// 清空;
    		for (i = 0; i < tmp.length; i++) {
    			tmp[i] = 0;
    		}
    	}
    
    	/**
    	 * 打印;
    	 * 
    	 * @param arr
    	 */
    	private static void printArr(int[] arr) {
    		for (int i : arr) {
    			System.out.print(i + " ");
    		}
    		System.out.println();
    	}
    
    }
    
    

    运行

    结果

    多思考,多尝试。
  • 相关阅读:
    BZOJ-1497 最大获利
    POJ-3680 Intervals & NOI 2008 志愿者招募 费用流
    CodeForces 663E Binary Table
    南昌区域赛-G Eating Plan
    HDU-5909 Tree Cutting
    BZOJ-4589 Hard Nim
    UVA-12633 Super Rooks on Chessboard
    SPOJ-TSUM Triple Sums
    HDU-4609 3-idiots
    Kattis-aplusb A+B problem
  • 原文地址:https://www.cnblogs.com/LynnMin/p/9545136.html
Copyright © 2011-2022 走看看