插入排序与希尔排序

来源:互联网 发布:ol3vs数据库app最新版 编辑:程序博客网 时间:2024/05/21 11:18




package com.demo.utils;  
  
//排序  
public class Sort {  
  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        int[] a = { 11, 3, 1, 5, 7, 9, 2, 4, 6, 8, 10 };  
        InsertSort(a);  
    }  
  
    // 插入排序  
    public static int[] InsertSort(int[] a) {  
  
        for (int index = 0; index < a.length; index++) {  
            // 当前指针  
            int subIndex = index;  
            int currentData = a[index]; // 等待插入的数据  
            while ((subIndex > 0) && (a[subIndex - 1] > currentData)) {  
                a[subIndex] = a[subIndex - 1];  
                subIndex--;  
            }  
            a[subIndex] = currentData; // 插入到合适的位置  
        }  
        printArray(a);  
        return a;  
    }  
  
    // 希尔排序  
    public static int[] shellSort(int[] a) {  
        int h = 1;  
        int tempData;  
  
        // 计算分成几组  
        while (h <= a.length / 3) {  
            h = h * 3 + 1;  
        }  
  
        while (h > 0) {  
            for (int pointer = h; pointer < a.length; pointer++) {  
                tempData = a[pointer];  
                while (pointer > h - 1 && a[pointer - h] >= tempData) {  
                    a[pointer] = a[pointer - h];  
                    pointer = pointer - h;  
                }  
                a[pointer] = tempData;  
            }  
            h = (h - 1) / 3;  
        }  
        printArray(a);  
        return a;  
    }  
  
    // 打印数组  
    public static void printArray(int[] a) {  
        for (int i = 0; i < a.length; i++) {  
            System.out.print(a[i] + " ");  
        }  
        System.out.println("");  
    }  
}
0 0
原创粉丝点击