Heap Sort Algorithm Source

package heapSort;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

public class Star {

	public static void main(String args[]) {

		ArrayList<String> data = new ArrayList<String>();
		String file_open_path = "D:/heapData.txt";

		fileRead(file_open_path, data);
		
		System.out.println(data);
		data = heapSort(data);
		System.out.println(data);

	}

	public static ArrayList<String> heapDown(ArrayList<String> data) {
		for (int n = (data.size() / 2) - 1; n >= 0; n--) {
			int leftChild = (n * 2) + 1;
			int rightChild = (n * 2) + 2;

			if (data.get(leftChild).compareTo(data.get(n)) < 0) {
				swapData(data, n, leftChild);
			}

			if (rightChild < data.size()) {
				if (data.get(rightChild).compareTo(data.get(n)) < 0) {
					swapData(data, n, rightChild);
				}
			}
		}
		return data;
	}

	public static ArrayList<String> heapSort(ArrayList<String> data) {
		ArrayList<String> sortedData = new ArrayList<String>();

		int len = data.size();
		data = heapDown(data);

		for (int i = 0; i < len; i++) {
			sortedData.add(0, data.remove(0));
			data = heapDown(data);
		}
		return sortedData;
	}

	private static void fileRead(String path, List<String> data) {
		BufferedReader reader = null;

		if (path != null) {
			try {
				reader = new BufferedReader(new FileReader(path));

				String line = null;
				while ((line = reader.readLine()) != null) {
					if (line.charAt(0) == 65279) {
						data.add(new String(new StringBuffer(line)
								.deleteCharAt(0)));
					} else {
						data.add(line);
					}
				}
				reader.close();
			} catch (Exception e) {
				System.err.println(e);
			} finally {
				try {
					if (reader != null) {
						reader.close();
					}
				} catch (Exception ex) {
				}
			}
		}
	}

	private static void swapData(ArrayList<String> data, int a, int b) {
		String temp;
		temp = data.get(a);
		data.set(a, data.get(b));
		data.set(b, temp);
	}
}


+ Recent posts