几种sort算法的Java实现

InsertionSort

插入排序
import java.util.Arrays;

public class InsertionSort {
    public static void main(String[] args) {
        int[] a = new int[10];
        populateArray(a);
        printArray(a);
        insertionSort(a);
        System.out.println();
        printArray(a);
    }

    private static void insertionSort(int[] a) {
        // TODO Auto-generated method stub
        for (int i = 1; i < a.length; i++) 
        {
            int value = a[i];
            int j = i;
            
            while (j > 0 && a[j - 1] > value) 
            {
                a[j] = a[j - 1];
                j--;
            }
            a[j] = value;
        }
    }

    private static void printArray(int[] a) {
        // TODO Auto-generated method stub
        System.out.println(Arrays.toString(a));
    }

    private static void populateArray(int[] arr) {
        // TODO Auto-generated method stub
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * 100);
        }
    }
}

 

后续的几种排序以后会逐渐补充....

2014-10-16 23:41:28


 

posted on 2014-01-15 20:20  jinfenglee  阅读(163)  评论(0编辑  收藏  举报

导航