堆排序

/**
 * <ul>
 * <li>平均情况:O(nlog(2)n)</li>
 * <li>最好情况:O(nlog(2)n)</li>
 * <li>最坏情况:O(nlog(2)n)</li>
 * <li>辅助存储:O(1)</li>
 * <li>不稳定</li>
 * <ul>
 * 
 * @timestamp Mar 12, 2016 6:56:54 PM
 * @author smallbug
 */
public class HeadSort {

	public static void main(String[] args) {
		int[] data = DataUtil.getData(100000);
		// System.out.println(Arrays.toString(data));
		long time = System.currentTimeMillis();
		headSort(data);
		// System.out.println(Arrays.toString(data));
		System.out.println("speed " + (System.currentTimeMillis() - time) + " ms");
		System.out.println("排序是否成功:" + (DataUtil.verify(data, DataUtil.DESC) ? "是" : "否"));
	}

	private static void headSort(int[] data) {
		createHead(data);
		for (int i = data.length - 1; i > 0; i--) {
			sort(data, i);
		}
	}

	private static void sort(int[] data, int i) {
		DataUtil.swap(data, 0, i);
		siftDown(data, i);
	}

	private static void siftDown(int[] data, int border) {
		int left = 2;
		int index = 1;
		int temp = data[0];
		while (left < border) {
			if (data[left - 1] > data[left]) {// 左边大于右边,跟右边比较
				if (temp > data[left]) {
					data[index - 1] = data[left];
					index = left + 1;
					left = (left + 1) << 1;
				} else
					break;
			} else {
				if (temp > data[left - 1]) {// 跟左边比较
					data[index - 1] = data[left - 1];
					index = left;
					left <<= 1;
				} else
					break;
			}
		}
		data[index - 1] = temp;
	}

	private static void createHead(int[] data) {
		for (int i = 0; i < data.length; i++) {
			siftUp(data, i + 1);
		}
	}

	/**
	 * 
	 * @timestamp Mar 12, 2016 8:32:39 PM
	 * @param data
	 *            数据
	 * @param index
	 *            操作索引+1
	 */
	private static void siftUp(int[] data, int index) {
		int temp = data[index - 1];
		int parent = index >>> 1;
		while (parent > 0) {
			if (temp < data[parent - 1]) {
				data[index - 1] = data[parent - 1];
				index = parent;
				parent = parent >>> 1;
			} else
				break;
		}
		data[index - 1] = temp;
	}

}

 

你可能感兴趣的:(数据结构,堆排序)