经典排序算法(希尔排序,归并排序,快速排序,插入排序)

	public static void main(String[] args){
		int[]a={13,50,6,9,8,7,12,15,100,4};
		//insertSort(a);
		//shellSort(a);
		//quickSort1(a,0,a.length-1);
		int []temp=new int[a.length];
		mergeSort(a,0,a.length-1,temp);
		for(int cc:a)
		{
			System.out.print(cc+"  ");
		}
	}
	public static void insertSort(int[] a){
		int key=0;
		int i=0;
		for(int j=2;j<a.length;j++){
			key=a[j];
			i=j-1;
			while(i>=0&&a[i]>key){
				a[i+1]=a[i];
				i--;
			}
			a[i+1]=key;
		}
	}
	public static void shellSort(int[] a){
		int size=a.length;
		for(int gap=size/2;gap>=1;gap/=2){
			for(int i=gap;i<size;i++){
				int temp=a[i];
				int k;
				for(k=i-gap;k>=0&&a[k]>temp;k-=gap){
					a[k+gap]=a[k];
				}
				a[k+gap]=temp;
			}
		}
	}
	public static void quickSort1(int[] a,int L,int R){
		if(L<R){
			int i=L,j=R,key=a[L];
			while(i<j){
				while(i<j&&a[j]>=key){
					j--;
				}
				if(i<j){
					a[i++]=a[j];
				}
				while(i<j&&a[i]<key){
					i++;
				}
				if(i<j){
					a[j--]=a[i];
				}
			}
			a[i]=key;
			quickSort1(a,L,i-1);
			quickSort1(a,i+1,R);
		}
	}
	//合并数组
	public static void mergeSort(int a[],int first,int mid,int end,int[] temp){
		int i=first,j=mid+1;
		int m=mid,n=end;
		int k=0;
		while(i<=m&&j<=n){
			if(a[i]<=a[j]){
				temp[k++]=a[i++];
			}else{
				temp[k++]=a[j++];
				//count+=m-i+1;          还可以统计逆序对,n*lgn时间复杂度
			}
		}
		while(i<=m){
			temp[k++]=a[i++];
		}
		while(j<=n){
			temp[k++]=a[j++];
		}
		for(i=0;i<k;i++){
			a[first+i]=temp[i];
		}	
	}
	public static void mergeSort(int[] a,int first,int last,int[] temp){
		if(first<last){
			int mid=(first+last)/2;
			mergeSort(a,first,mid,temp);
			mergeSort(a,mid+1,last,temp);
			mergeSort(a,first,mid,last,temp);
		}
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值