美文网首页
JAVA堆排序(HEAP-SORT)

JAVA堆排序(HEAP-SORT)

作者: 龙儿筝 | 来源:发表于2017-03-31 09:34 被阅读42次
    public class HeapSort {
        public static void heapSort(int[] array) {
            if (null == array || array.length < 2) {
                return;
            }
            int index;
            for (int i = 0; i < array.length; i++) {
                index = array.length - i - 1;
                maxHeap(array, index);
                if (index != 0) {
                    array[0] ^= array[index];
                    array[index] ^= array[0];
                    array[0] ^= array[index];
                }
            }
        }
    
        private static void maxHeap(int[] array, int lastIndex) {
            int k;
            int index = (lastIndex - 1) / 2;
            for (int i = index; i > -1; i--) {
                k = i;
                while (2 * k <= lastIndex - 1) {
                    int biggerIndex = 2 * k + 1;
                    if (biggerIndex < lastIndex && array[biggerIndex] < array[biggerIndex + 1]) {
                        biggerIndex++;
                    }
                    if (array[k] < array[biggerIndex]) {
                        array[k] ^= array[biggerIndex];
                        array[biggerIndex] ^= array[k];
                        array[k] ^= array[biggerIndex];
                        k = biggerIndex;
                    } else {
                        break;
                    }
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:JAVA堆排序(HEAP-SORT)

          本文链接:https://www.haomeiwen.com/subject/kxvmottx.html