栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

排序算法---堆排序

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

排序算法---堆排序

public class Demo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] aa = getsz(10, 10, 20);
		for (int i = 0; i < aa.length; i++) {
			System.out.print(aa[i]+" ");
		}
		System.out.println();
		int[] bb = heapsork(aa);
		for (int i = 0; i < bb.length; i++) {
			System.out.print(bb[i]+" ");
		}

	}
	public static int[] heapsork(int[] num) {
		makemaxheap(num);
		int temp = 0;
		int j = 1;
		for (int i = num.length-1; i > 0&&j
			temp = num[i];
			num[i] = num[0];
			num[0] = temp;
			downid(num,0,num.length-j);
		}
		return num;
	}
	
	public static int[] makemaxheap(int[] Num) {
		int length = Num.length;
		for (int i = length/2-1; i > -1; i--) {
			downid(Num,i,length);
		}
		return Num;
	}

	public static void downid(int[] num, int i,int length) {
		// TODO Auto-generated method stub
		
		int left = 2*i+1;
		int right = 2*i+2;
		int max = left;
		if (left>=length) {
			return;
		}
		
		if (right>=length) {
			 max = left;
		}else if (num[right]>num[left]) {
			max = right;
		}
		
		if (num[i]>num[max]) {
			return;
		}else {
			int temp = num[max];
			num[max] = num[i];
			num[i] = temp;
		}
		downid(num,max,length);
	}
	
	public static int[] getsz(int length,int min,int max) {
		int[] sz = new int[length];
		for (int i = 0; i < sz.length; i++) {
			sz[i] = (int)(Math.random()*max);	 
		}		
		return sz;
	}

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/964354.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号