Merge sort-java

Indique a fonte para reimpressão: http://blog.csdn.net/lx1848/article/details/51408085

1. Crie uma classe SortAlgorithm.java e copie o código a seguir nela.

2. Crie um arquivo DATA2 no mesmo diretório , e salve os números para serem ordenados nele, separados por espaços.

Quanto à teoria do tipo de mesclagem, não vou falar muito, existem muitos artigos semelhantes.

O conteúdo principal do algoritmo de classificação por mesclagem está na classe aninhada MergeSort.

Extensão: se o logaritmo reverso nesses dados for necessário, você pode encontrá-lo com a ajuda de merge sort? dicas: Considere na fusão de métodos.

package sorting;

import java.io.*;
import java.util.Arrays;

/**
 * Created by lx on 2016/5/14.
 */
public class SortAlgorithm {
    static class MergeSort {
        public static void mergeSort(Comparable a[], int left, int right) {
            if(a == null) {
                throw new NullPointerException("input a is null");
            }
            if(left > right || left < 0 || right >= a.length) {
                System.err.println("Usage: mergeSort(a, left, right), in which 0 <= left < right <= a.length-1 ");
                return;
            }
            if(left < right) {
                Comparable b[] = new Comparable[right-left+1];
                //int i = (left + right) / 2;
                //avoid i is too large that out range of int
                int i = (left+right) >> 1;
                mergeSort(a,i+1,right);
                mergeSort(a,left,i);
                merge(a,b,left,i,right);
                copy(a,b,left,right);
            }
        }
        //merge two into b
        public static void merge(Comparable a[],Comparable b[], int left, int mid, int right) {
            int i, j, k = 0;
            i = left;
            j = mid+1;
            while (i <= mid && j <= right) {
                if(a[i].compareTo(a[j]) > 0) {
                    b[k++] = a[j++];
                } else {
                    b[k++] = a[i++];
                }
            }
            while (i <= mid) {
                b[k++] = a[i++];
            }
            while (j <= right) {
                b[k++] = a[j++];
            }
        }
        //copy b back to a
        public static void copy(Comparable a[],Comparable b[], int left, int right) {
            int j = 0;
            //while(j < b.length)
            while(j < (right-left + 1)) {
                a[j+left] = b[j++];
            }
        }
    }

    public static Integer[] readData() {
        Comparable[] a = null;
        try {
			//文件DATA2中保存的是待排序的数据,以空格隔开
            FileReader fr = new FileReader(new File(".\\DATA2"));
            BufferedReader br = new BufferedReader(fr);
            StringBuilder stringBuilder = new StringBuilder();
            String str;
            while((str = br.readLine()) != null) {
                stringBuilder.append(str + " ");
            }
            String[] temp = stringBuilder.toString().split("\\s+");
            a = new Integer[temp.length];
            int i = 0;
            while (i < temp.length) {
                a[i] = Integer.parseInt(temp[i]);
                i++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (Integer[])a;
    }

    public static void main(String[] args) {
        //Integer a[] = { 2, 7, 8, 3, 1, 6, 9, 0, 5, 4 };
        Integer[] a;
        a = readData();
        MergeSort demo = new MergeSort();
		//各种输入测试
		//a = null
//      demo.mergeSort(null,0,100);
		//left > right
//      demo.mergeSort(a, a.length-1, 0);
		//left = right
//		demo.mergeSort(a,a.length,a.length-1);
        System.out.println("sorting " + a.length + " numbers: " + Arrays.toString(a));
        demo.mergeSort(a,0,a.length-1);
        System.out.println("sorted " + a.length + " numbers: " + Arrays.toString(a));
    }
}


Acho que você gosta

Origin blog.csdn.net/lx1848/article/details/51408085
Recomendado
Clasificación