1. 程式人生 > >桶排序(heap sort)-Java實現

桶排序(heap sort)-Java實現

public static void heapSort(int[] a) {
		int i, j, k;
		int temp;
		int n = a.length;
		for (i = n / 2 - 1; i >= 0; i--) {
			while (2 * i + 1 < n) {
				j = 2 * i + 1;
				if (j + 1 < n)
					if (a[j] < a[j + 1])
						j++;
				if (a[i] < a[j]) {
					temp = a[i];
					a[i] = a[j];
					a[j] = temp;
					i = j;
				} else
					break;
			}
		}
		for (i = n - 1; i > 0; i--) {
			temp = a[0];
			a[0] = a[i];
			a[i] = temp;
			k = 0;
			while (2 * k + 1 < i) {
				j = 2 * k + 1;
				if (j + 1 < i)
					if (a[j] < a[j + 1])
						j++;
				if (a[k] < a[j]) {
					temp = a[k];
					a[k] = a[j];
					a[j] = temp;
					k = j;
				} else
					break;
			}
		}
	}