插入排序与希尔排序--java实现

一  插入排序

package test;

public class InsertSort {
	//3.直接插入排序法
	/**
	  	稳定 
		空间复杂度O(1) 
		时间复杂度O(n2) 
		最差情况:反序,需要移动n*(n-1)/2个元素 
		最好情况:正序,不需要移动元素
	 */
	
	
  /*1从第一个元素开始,该元素可以认为已经被排序
	2取出下一个元素,在已经排序的元素序列中从后向前扫描
	3如果该元素小于前面的元素(已排序),则依次与前面元素进行比较如果小于则交换,直到找到大于该元素的就则停止;
	4如果该元素大于前面的元素(已排序),则重复步骤2
	5重复步骤2~4 直到所有元素都排好序 。*/
	//时间复杂度(n*n)  最好情况的时间复杂度n
	
	public static void insertSort(int []arr){
		int temp=0;
		for(int i=1;i<arr.length;i++){//比较length-1次
			
			temp=arr[i];
			int j=i-1;
			while(j>=0 && temp<arr[j]){//如果第二个元素小于第一个元素
				arr[j+1]=arr[j];//将元素往后面移动一位
				j--;
			}
			arr[j+1]=temp;//最小的元素放到第一个位置
		}
	}
	public static void main(String[] args) {
		int arr[]={6,45,9,8,39,-9,1,2,9,6};
		insertSort(arr);
		for (int i : arr) {
			System.out.print(i+" ");
		}
	}
	
}

二 希尔排序

不同的希尔增量

package test;

public class ShellSort {
	public static void shellSort(int[] a){
        int d  = a.length;
        while (d!=0) {
            d=d/2;
            for (int x = 0; x < d; x++) {//分的组数
                for (int i = x + d; i < a.length; i += d) {//组中的元素,从第二个数开始
                    int j = i - d;//j为有序序列最后一位的位数
                    int temp = a[i];//要插入的元素
                    for (; j >= 0 && temp < a[j]; j -= d) {//从后往前遍历。
                        a[j + d] = a[j];//向后移动d位
                    }
                    a[j + d] = temp;
                }
            }
        }
    }
	public static void main(String[] args) {
	

		int arr[]={6,45,9,8,39,-9,1,2,9,6};
		shellSort(arr);
		for (long i : arr) {
			System.out.print(i+" ");
		}
	}
}
package ch04;

public class ShellSort {
	
	public static void shellSort(long[] arr){
		//初始化一个间隔
		int h=1;
		//计算最大间隔
		while(h < arr.length/3){
			h=h*3+1;
		}
		while(h > 0){
			//进行插入排序
			long tmp=0;
			for(int i=h;i < arr.length;i++){
				tmp=arr[i];
				int j=i;
				while(j > h-1 && arr[j-h]>=tmp){
					arr[j]=arr[j-h];
					j=j-h;
				}
				arr[j]=tmp;
			}
			//减小间隔
			h=(h-1)/3;
		}
	}
	public static void main(String[] args) {
		long arr[]={6,45,9,8,39,-9,1,2,9,6};
		shellSort(arr);
		for (long i : arr) {
			System.out.print(i+" ");
		}
	}
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值