Sorting - JAVA implementation [four] heap sorting

package org.lion.euler.study.sort;

/**
 * heap sort
 *
 * Principle: Create a large top heap, exchange the first and last values, and re-maintain the large top heap.
 * @author lion
 *
 */
public class HeapSort extends AbstractSort {

	@Override
	public void sort(Integer[] array) {
		int len = array.length/2;
		while(len >= 0){
			this.heapMax(array, len, array.length);
			len - = 1;
		}
		
		int curLen = array.length - 1;
		while(curLen >= 0){
			this.swap(array, 0, curLen);
			this.heapMax(array, 0, curLen);
			
			curLen - = 1;
		}
		
	}
	
	private void heapMax(Integer[] array, int index, int maxLen){
		int len = maxLen;
		int curIndex = index;
		while (curIndex <len) {
			int left = curIndex * 2;
			int right = left + 1;
			
			int maxIndex = curIndex;
			if(left < len && array[left] > array[maxIndex]){
				maxIndex = left;
			}
			if(right < len && array[right] > array[maxIndex]){
				maxIndex = right;
			}
			if(maxIndex > curIndex){
				this.swap(array, curIndex, maxIndex);
				curIndex = maxIndex;
			}else{
				break;
			}
		}
	}
	
	

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325981275&siteId=291194637