首页 > 学院 > 开发设计 > 正文

【算法】程序猿不写代码是不对的19

2019-11-08 01:48:07
字体:
来源:转载
供稿:网友
package com.kingdz.algorithm.time201702;import java.util.Arrays;/** * 堆排序 *  * @author kingdz *  */public class Algo20 {	public static void main(String[] args) {		int count = 10;		int[] number = new int[count];		number = Algo13.fillArray(count, false);		System.out.PRintln(Arrays.toString(number));		genHeap(number);		heapSort(number);	}	/**	 * 生成堆	 * 	 * @param copy	 */	private static void genHeap(int[] copy) {		// System.out.println(Arrays.toString(copy));		// print(copy);		for (int i = copy.length - 1; i > 1; i--) {			int isChange = 0;			if (i % 2 != 0) {				isChange = sortThree(copy, i / 2, i - 1, i);			} else {				isChange = sortThree(copy, i / 2, i);			}			if (isChange != 0) {				i = copy.length;			}		}		System.out.println(Arrays.toString(copy));		// print(copy);	}	/**	 * 三个数字排序	 * 	 * @param copy	 * @param a	 * @param b	 * @param c	 * @return	 */	private static int sortThree(int[] copy, int a, int b, int c) {		int j = c;		if (copy[b] < copy[c]) {			j = b;		}		return sortThree(copy, a, j);	}	/**	 * 两个数字排序	 * 	 * @param copy	 * @param a	 * @param b	 * @return	 */	private static int sortThree(int[] copy, int a, int b) {		if (copy[a] < copy[b]) {			Algo13.swap(copy, a, b);			return 1;		}		return 0;	}	/**	 * 复制数组,也就是将数组后移一位	 * 	 * @param number	 * @return	 */	private static int[] moveArray(int[] number) {		int[] copy = new int[number.length + 1];		for (int i = 1; i < number.length + 1; i++) {			copy[i] = number[i - 1];		}		return copy;	}	/**	 * 实际运行的堆排序	 * 	 * @param number	 */	private static void heapSort(int[] number) {		int[] copy = moveArray(number);		for (int i = 0; i < number.length; i++) {			// 生成堆			genHeap(copy);			// 输出第一个元素,从0开始计数,第0个位置为0代表没有元素			System.out.println(copy[1]);			// 将最后一个元素复制到第一个位置			int index = number.length;			while (copy[index] == 0) {				index--;			}			if (index > 1) {				copy[1] = copy[index];				// 将最后一个元素赋值为0				copy[index] = 0;			}		}	}}
上一篇:UVA - 242 线性DP

下一篇:Groovy方法合成

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表