程序员必知的8大排序(java实现)(一)(插入+希尔+简单选择)

来源:互联网 发布:人体断层解剖学软件 编辑:程序博客网 时间:2024/03/27 13:01
8种排序之间的关系:
程序员必知的8大排序(java实现) - kevin - 初生牛犊

1、 直接插入排序

(1)基本思想:

  在要排序的一组数中,假设前面(n-1)[n>=2] 个数已经是排好顺序的,现在要把第n个数插到前面的有序数中,使得这n个数也是排好顺序的。如此反复循环,直到全部排好顺序。

  (2)实例

程序员必知的8大排序(java实现) - kevin - 初生牛犊

(3)用java实现

public class insertSort {public insertSort() {int[] a = { 49, 38, 57, 63, 46, 15, 85, 93, 24, 67 };int temp = 0;for (int i = 0; i < a.length; i++) {temp = a[i];int j = i - 1;for (; j >= 0 && a[j] > temp; j--) {a[j + 1] = a[j];}a[j + 1] = temp;}for (int i = 0; i < a.length; i++) {System.out.print(a[i] + " ");}}public static void main(String[] args) {insertSort is = new insertSort();}}


2、希尔排序(最小增量排序)

(1)基本思想:

  算法先将要排序的一组数按某个增量d(n/2,n为要排序数的个数)分成若干组,每组中记录的下标相差d.对每组中全部元素进行直接插入排序,然后再用一个较小的增量(d/2)对它进行分组,在每组中再进行直接插入排序。当增量减到1时,进行直接插入排序后,排序完成。

(2)实例

程序员必知的8大排序(java实现) - kevin - 初生牛犊

(3)用java实现

public class shellSort {
public  shellSort(){
    int a[]={1,54,6,3,78,34,12,45,56,100};
    double d1=a.length;
    int temp=0;
    while(true){
        d1= Math.ceil(d1/2);
        int d=(int) d1;
        for(int x=0;x<d;x++){
            for(int i=x+d;i<a.length;i+=d){
                int j=i-d;
                temp=a[i];
                for(;j>=0&&temp<a[j];j-=d){
                a[j+d]=a[j];
                }
                a[j+d]=temp;
            }
        }
        if(d==1)
            break;
    }
    for(int i=0;i<a.length;i++)
        System.out.println(a[i]);
}
}

3、简单选择排序

(1)基本思想:

  在要排序的一组数中,选出最小的一个数与第一个位置的数交换;然后在剩下的数当中再找最小的与第二个位置的数交换,如此循环到倒数第二个数和最后一个数比较为止。

(2)实例:

程序员必知的8大排序(java实现) - kevin - 初生牛犊

(3)用java实现

public class selectSort {public selectSort() {int[] a = { 1, 35, 47, 86, 93, 53, 67, 73, 25, 69 };int position = 0;for (int i = 0; i < a.length - 1; i++) {int j = i + 1;position = j;int temp = a[i];for (; j < a.length - 1; j++) {if (a[j] < temp) {temp = a[j];position = j;}}a[position] = a[i];a[i] = temp;}for (int i = 0; i < a.length; i++)System.out.print(a[i] + " ");}public static void main(String[] args) {selectSort ses = new selectSort();}}

0 0