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

来源:互联网 发布:网站在线客服系统源码 编辑:程序博客网 时间:2024/05/16 01:35
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];// 将最后一个元素赋值为0copy[index] = 0;}}}}

0 0