Java堆和堆排序代码整理

说明: 对java数据结构中的堆的有关代码整理了一下,以备使用~~~

1. 堆结点:

package boke.heap;

/**
 * 堆结点
 * 
 * @since jdk1.5及其以上
 * @author 毛正吉
 * @version 1.0
 * @date 2010.05.24
 * 
 */
public class Node {
	private int iData; // 结点数据是整型

	public Node(int key) {
		iData = key;
	}

	/**
	 * setKey
	 * 
	 * @param id
	 */
	public void setKey(int id) {
		iData = id;
	}

	/**
	 * getKey
	 * 
	 * @return
	 */
	public int getKey() {
		return iData;
	}
}

2. 堆容器:

package boke.heap;

/**
 * 堆
 * 
 * @since jdk1.5及其以上
 * @author 毛正吉
 * @version 1.0
 * @date 2010.05.24
 * 
 */
public class Heap {
	private Node[] heapArray; // 堆容器
	private int maxSize; // 堆得最大大小
	private int currentSize; // 堆得大小

	/**
	 * 构造
	 * 
	 * @param _maxSize
	 */
	public Heap(int _maxSize) {
		maxSize = _maxSize;
		currentSize = 0;
		heapArray = new Node[maxSize];

	}

	/**
	 * 堆是否为空
	 * 
	 * @return
	 */
	public boolean isEmpty() {
		return currentSize == 0;
	}

	/**
	 * 在堆中插入新元素
	 * 
	 * @param key
	 * @return
	 */
	public boolean insert(int key) {
		if (currentSize == maxSize) {
			return false;
		}
		Node newNode = new Node(key);
		heapArray[currentSize] = newNode;
		trickleUp(currentSize++);
		return true;
	}

	/**
	 * 堆调整自下而上的调整
	 * 
	 * @param index
	 */
	public void trickleUp(int index) {
		int parent = (index - 1) / 2;
		Node bottom = heapArray[index];

		while (index > 0 && heapArray[parent].getKey() < bottom.getKey()) {
			heapArray[index] = heapArray[parent]; // 双亲结点值大, 调整
			index = parent;
			parent = (parent - 1) / 2;
		}
		heapArray[index] = bottom; // 回送
	}

	/**
	 * 删除堆中最大的值
	 * 
	 * @return
	 */
	public Node remove() {
		Node root = heapArray[0];
		heapArray[0] = heapArray[--currentSize];
		trickleDown(0);
		return root;
	}

	/**
	 * 自上而下的调整
	 * 
	 * @param index
	 */
	public void trickleDown(int index) {
		int largeChild;
		Node top = heapArray[index]; // save root
		while (index < currentSize / 2) { // while node has at least one child
			int leftChild = 2 * index + 1;
			int rightChild = leftChild + 1;

			if (rightChild < currentSize
					&& heapArray[leftChild].getKey() < heapArray[rightChild]
							.getKey()) {
				largeChild = rightChild;
			} else {
				largeChild = leftChild;
			}

			if (top.getKey() >= heapArray[largeChild].getKey()) {
				break;
			}

			heapArray[index] = heapArray[largeChild]; // shift child up
			index = largeChild; // go down
		}
		heapArray[index] = top; // root to index
	}

	/**
	 * 改变堆中索引为index处的值
	 * 
	 * @param index
	 * @param newValue
	 * @return
	 */
	public boolean change(int index, int newValue) {
		if (index < 0 || index >= currentSize) {
			return false;
		}

		int oldValue = heapArray[index].getKey(); // remove old
		heapArray[index].setKey(newValue); // change to new

		if (oldValue < newValue) { // if raised
			this.trickleUp(index); // trickle it up
		} else { // if lowered
			this.trickleDown(index); // trickle it down
		}

		return true;
	}

	/**
	 * 按某种格式输出堆
	 */
	public void displayHeap() {
		System.out.print("heapArray: ");
		for (int i = 0; i < currentSize; i++) {
			if (heapArray[i] != null) {
				System.out.print(heapArray[i].getKey() + " ");
			} else {
				System.out.print("-- ");
			}
		}
		System.out.println();

		int nBlanks = 32; // heap format
		int itemsPerRow = 1;
		int column = 0;
		int j = 0; // current item
		String dots = "...............................";
		System.out.println(dots + dots); // dotted top line

		while (currentSize > 0) { // for each heap item
			if (column == 0) { // first item in row
				for (int k = 0; k < nBlanks; k++) { // preceding blanks
					System.out.print(" ");
				}
			}
			System.out.print(heapArray[j].getKey()); // display item

			if (++j == currentSize) { // done?
				break;
			}

			if (++column == itemsPerRow) { // end of row?
				nBlanks /= 2; // half the blanks
				itemsPerRow *= 2; // twice the items
				column = 0; // start over on
				System.out.println(); // next row
			} else { // next item on row
				for (int k = 0; k < nBlanks * 2 - 2; k++) {
					System.out.print(' '); // interim blanks
				}
			}
		}
		System.out.println("\n" + dots + dots);
	}

	/**
	 * 输出堆数组
	 */
	public void displayArray() {
		for (int j = 0; j < maxSize; j++) {
			System.out.print(heapArray[j].getKey() + " ");
		}
		System.out.println("");
	}

	/**
	 * 在堆中的索引index出设置新结点
	 * 
	 * @param index
	 * @param newNode
	 */
	public void insertAt(int index, Node newNode) {
		heapArray[index] = newNode;
	}

	/**
	 * 堆的大小增量
	 */
	public void incrementSize() {
		currentSize++;
	}
}

3. 堆应用测试

package boke.heap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 堆应用测试
 * 
 * @since jdk1.5及其以上
 * @author 毛正吉
 * @version 1.0
 * @date 2010.05.24
 * 
 */
public class HeapApp {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		int value, value2;
		Heap hp = new Heap(31);
		boolean success;

		hp.insert(70);
		hp.insert(40);
		hp.insert(50);
		hp.insert(20);
		hp.insert(60);
		hp.insert(100);
		hp.insert(80);
		hp.insert(30);
		hp.insert(10);
		hp.insert(90);

		while (true) {
			System.out.print("Enter first letter of ");
			System.out.print("show, insert, remove, change: ");
			int choice = getChar();

			switch (choice) {
			case 's':
				hp.displayHeap();
				break;
			case 'i':
				System.out.print("Enter value to insert: ");
				value = getInt();
				success = hp.insert(value);
				if (!success) {
					System.out.println("Can't insert; heap is full");
				}
				break;
			case 'r':
				if (!hp.isEmpty()) {
					hp.remove();
				} else {
					System.out.println("Can't remove; heap is empty");
				}
				break;
			case 'c':
				System.out.print("Enter current index of item: ");
				value = getInt();
				System.out.print("Enter new key: ");
				value2 = getInt();
				success = hp.change(value, value2);
				if (!success) {
					System.out.println("Invalid index");
				}
				break;
			default:
				System.out.println("Invalid entry\n");
			}
		}

	}

	/**
	 * 获得控制台输入流
	 * 
	 * @return
	 * @throws IOException
	 */
	public static String getString() throws IOException {
		return new BufferedReader(new InputStreamReader(System.in)).readLine();
	}

	/**
	 * 获得控制台输入字符
	 * 
	 * @return
	 * @throws IOException
	 */
	public static char getChar() throws IOException {
		return getString().charAt(0);
	}

	/**
	 * 获得控制台输入整型
	 * 
	 * @return
	 * @throws NumberFormatException
	 * @throws IOException
	 */
	public static int getInt() throws NumberFormatException, IOException {
		return Integer.parseInt(getString());
	}

}

4. 堆排序测试:

package boke.heap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 堆排序测试
 * 
 * @since jdk1.5及其以上
 * @author 毛正吉
 * @version 1.0
 * @date 2010.05.24
 * 
 */
public class HeapSortApp {

	/**
	 * @param args
	 * @throws IOException
	 * @throws NumberFormatException
	 */
	public static void main(String[] args) throws NumberFormatException,
			IOException {
		int size, j;
		System.out.print("Enter number of items: "); // 输入堆大小

		size = getInt();
		Heap hp = new Heap(size);

		for (j = 0; j < size; j++) { // 随机建立堆
			int random = (int) (Math.random() * 100);
			Node newNode = new Node(random);
			hp.insertAt(j, newNode);
			hp.incrementSize();
		}

		System.out.print("Random: ");
		hp.displayArray(); // 输出堆数组

		for (j = size / 2 - 1; j >= 0; j--) {
			hp.trickleDown(j);
		}

		System.out.print("Heap: "); // 输出堆
		hp.displayArray();
		hp.displayHeap();

		for (j = size - 1; j >= 0; j--) {
			Node largestNode = hp.remove();
			hp.insertAt(j, largestNode);
		}

		System.out.print("Sorted: "); // 输出排序后的数组(升序)
		hp.displayArray();

	}

	/**
	 * 获得控制台输入流
	 * 
	 * @return
	 * @throws IOException
	 */
	public static String getString() throws IOException {
		return new BufferedReader(new InputStreamReader(System.in)).readLine();
	}

	/**
	 * 获得控制台输入整型
	 * 
	 * @return
	 * @throws NumberFormatException
	 * @throws IOException
	 */
	public static int getInt() throws NumberFormatException, IOException {
		return Integer.parseInt(getString());
	}

}

你可能感兴趣的:(java,数据结构,J#,UP,HP)