12

Simple Insertion Sort 插入排序

/**
 * 将位置p上的元素向左移动,直到它在前p+1个元素中的正确位置被找到的地方
 * @param a an array of Comparable items
 */
public static <AnyType extends Comparable<? super AnyType>> void insertionSort(AnyType[] a) {
    int j;
    for (int p = 1; p < a.length; p++) {
        AnyType tmp = a[p];
        for (j = p; j > 0 && tmp.compareTo(a[j-1]) < 0; j--) {
            a[j] = a[j-1];
        }
        a[j] = tmp;
    }
    System.out.println(Arrays.toString(a));
}

Shell Sort 希尔排序

/**
 * @param a an array of Comparable items
 */
public static <AnyType extends Comparable<? super AnyType>> void shellSort(AnyType[] a) {
    int j;
    for (int gap = a.length / 2; gap > 0; gap /= 2) {
        for (int i = gap; i < a.length; i++) {
            AnyType tmp = a[i];
            for (j = i; j >= gap && tmp.compareTo(a[j - gap]) < 0; j -= gap) {
                a[j] = a[j - gap];
            }
            a[j] = tmp;
        }
    }
    System.out.println(Arrays.toString(a));
}

Binary Sort 二分排序

/**
 * @param a an array of Comparable items
 */
public static <AnyType extends Comparable<? super AnyType>> void binarySort(AnyType[] a) {
    Integer i,j;
    Integer low,high,mid;
    AnyType temp;
    for(i=1;i<a.length;i++){
        temp=a[i];
        low=0;
        high=i-1;
        while(low<=high){
        mid=(low+high)/2;
        if(temp.compareTo(a[mid]) < 0) {
            high=mid-1;
        } else {
            low=mid+1;
        }
        }
        for(j=i-1;j>high;j--)
        a[j+1]=a[j];
        a[high+1]=temp;
    }
    System.out.println(Arrays.toString(a));
}

Bubble Sort 冒泡排序

/**
 * @param a an array of Comparable items
 */
public static <AnyType extends Comparable<? super AnyType>> void bubbleSort(AnyType[] a) {
    Integer i,j;
    AnyType temp;  
    for(i=1;i<a.length;i++) {  
        for(j=0;j<a.length-i;j++) {       //循环找到下沉"气泡",每下沉一位,下次比较长度较小一位   
            if(a[j].compareTo(a[j+1]) > 0) {
                temp=a[j];  
                a[j]=a[j+1];  
                a[j+1]=temp;      //将"气泡"下沉到当前比较的最后一位   
            }  
        }  
    }  
    System.out.println(Arrays.toString(a));
}

Selection Sort 选择排序

/**
 * @param a an array of Comparable items
 */
public static <AnyType extends Comparable<? super AnyType>> void selectSort(AnyType[] a) {
    Integer i,j,min;
    AnyType temp;  
    for(i=0;i<a.length-1;i++) {  
        temp=a[i];            
        min=i;                   //将当前位置元素当作最小值元素(其实是要将最小值元素交换到当前)   
        for(j=i+1;j<a.length;j++) {  
            if(temp.compareTo(a[j]) > 0) { //用a[i]和后面所有元素逐个比较,找到最小指的下标并记录  
                temp=a[j];      //下一位小于前一位,则将下一位赋值给temp并继续往右移动比较   
                min=j;           //最小值的下标,赋值给min   
            }  
        }  
        a[min] = a[i];           //将最小值元素的和当前元素交换,使得当前元素为其后面所有元素中最小值     
        a[i] = temp;  
    }
    System.out.println(Arrays.toString(a));
}

nasuf
557 声望21 粉丝