Java排序算法优化--插入排序【温故而知新】

来源:互联网 发布:高性能网络编程 二 编辑:程序博客网 时间:2024/05/17 08:31
/** * * @author Fly */public class InsertSort {    public int[] insertSort(int[] a) {        int size = a.length;        int j;        for (int i = 1; i < size; i++) {            int temp = a[i];            for (j = 0; j < i; j++) {                if (a[i] < a[j]) {                    break;                }            }            for (int k = i; k > j; k--) {                a[k] = a[k - 1];            }            a[j] = temp;        }        return a;    }    public int[] insertSort1(int[] a) {        int size = a.length;        for (int i = 1; i < size; i++) {            //标记当前需要比较的元素,也就是当前无序数组中的第一个元素            //j是有序数组中小于a[i]的元素            int temp = a[i], j;            //循环继续的条件就是遇到比a[i]大的元素,如果没有了,说明找到了正确的位置            for (j = i; j > 0 && temp < a[j - 1]; j--) {                a[j] = a[j - 1];            }            //把a[i]的值给找到的那个元素            a[j] = temp;            //其实这是一个连续交换的过程        }        return a;    }    public void printArray(int[] a) {        for (int i : a) {            System.out.print(i + ",");        }        System.out.println();    }    public static void main(String[] args) {        int[] a = {2, 3, 1, 5, 7, 8, 9, 0, 11, 10, 12, 13, 14, 4, 6};        InsertSort insertSort = new InsertSort();        insertSort.printArray(a);        insertSort.printArray(insertSort.insertSort(a));        insertSort.printArray(insertSort.insertSort1(a));    }}

0 0
原创粉丝点击