堆排序的应用

昨天总结了一下几种常用的排序算法,而且,在比较排序算法的结尾有一个小tips:堆排序和归并排序都是渐进最有的比较排序算法。今天在回顾算法导论的过程中发现,堆排序,快排,归并排序的应用很广泛,重要的不是这种排序的方式,而是这种排序的思想值得我们学习。

比如堆排序常用于中位数的查找,以及找出给定数组中最大(小)的k个数。

首先我们先来思考一下这个数组中最小的k个数。一般比较暴力的思想就是使用快排,然后找出前k个数输出即可。这样的时间复杂度是O(nlog_n).这样很容易理解。这里采用堆排序的方法,既然是堆排序,我们就要考虑是大顶堆还是小顶堆呢?当然,我们想要的结果的大小是k,所以堆的大小选择为k。构造小顶堆的话,堆顶元素一直是最小的。我们无法确定第k小的数是多少,所以是行不通的。这里可以使用大顶堆,大小为k,堆顶元素是k个元素中最大的,我们依次对数组元素进行遍历。不断地与堆顶元素进行比较,一旦该值小于堆顶元素,则弹出堆顶元素,并将该值加入堆中,堆排序一次。持续此方法,直到数组末尾。

代码如下:

import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
   public ArrayList GetLeastNumbers_Solution(int[] input, int k) {
       ArrayList result = new ArrayList();
       int length = input.length;
       if(k > length || k == 0){
           return result;
       }
        PriorityQueue maxHeap = new PriorityQueue(k, new Comparator() {
 
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });
        for (int i = 0; i < length; i++) {
            if (maxHeap.size() != k) {
                maxHeap.offer(input[i]);
            } else if (maxHeap.peek() > input[i]) {
                Integer temp = maxHeap.poll();
                temp = null;
                maxHeap.offer(input[i]);
            }
        }
        for (Integer integer : maxHeap) {
            result.add(integer);
        }
        return result;
    }
}

对于中位数,很相似。只不过是输出元素个数问题。这里要用到两个堆。为啥要用两个堆呢?难道一个不行吗?这个疑问挺好,其实是因为数组长度为奇数或者偶数的处理方式不一样吧。所以我们要用两个堆,一个大顶堆,一个小顶堆。大顶堆用来存比较小的数,小顶堆用来存比较大的数,这样到最后,我们可以将两个堆顶元素相加然后得出结果。附代码:

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class MadianQuick {

	public static class MedianHolder {
		private PriorityQueue maxHeap = new PriorityQueue(new MaxHeapComparator());
		private PriorityQueue minHeap = new PriorityQueue(new MinHeapComparator());

		private void modifyTwoHeapsSize() {
			if (this.maxHeap.size() == this.minHeap.size() + 2) {
				this.minHeap.add(this.maxHeap.poll());
			}
			if (this.minHeap.size() == this.maxHeap.size() + 2) {
				this.maxHeap.add(this.minHeap.poll());
			}
		}

		public void addNumber(int num) {
			if (this.maxHeap.isEmpty()) {
				this.maxHeap.add(num);
				return;
			}
			if (this.maxHeap.peek() >= num) {
				this.maxHeap.add(num);
			} else {
				if (this.minHeap.isEmpty()) {
					this.minHeap.add(num);
					return;
				}
				if (this.minHeap.peek() > num) {
					this.maxHeap.add(num);
				} else {
					this.minHeap.add(num);
				}
			}
			modifyTwoHeapsSize();
		}

		public Integer getMedian() {
			int maxHeapSize = this.maxHeap.size();
			int minHeapSize = this.minHeap.size();
			if (maxHeapSize + minHeapSize == 0) {
				return null;
			}
			Integer maxHeapHead = this.maxHeap.peek();
			Integer minHeapHead = this.minHeap.peek();
			if (((maxHeapSize + minHeapSize) & 1) == 0) {
				return (maxHeapHead + minHeapHead) / 2;
			}
			return maxHeapSize > minHeapSize ? maxHeapHead : minHeapHead;
		}

	}

	public static class MaxHeapComparator implements Comparator {
		@Override
		public int compare(Integer o1, Integer o2) {
			if (o2 > o1) {
				return 1;
			} else {
				return -1;
			}
		}
	}

	public static class MinHeapComparator implements Comparator {
		@Override
		public int compare(Integer o1, Integer o2) {
			if (o2 < o1) {
				return 1;
			} else {
				return -1;
			}
		}
	}

	// for test
	public static int[] getRandomArray(int maxLen, int maxValue) {
		int[] res = new int[(int) (Math.random() * maxLen) + 1];
		for (int i = 0; i != res.length; i++) {
			res[i] = (int) (Math.random() * maxValue);
		}
		return res;
	}

	// for test, this method is ineffective but absolutely right
	public static int getMedianOfArray(int[] arr) {
		int[] newArr = Arrays.copyOf(arr, arr.length);
		Arrays.sort(newArr);
		int mid = (newArr.length - 1) / 2;
		if ((newArr.length & 1) == 0) {
			return (newArr[mid] + newArr[mid + 1]) / 2;
		} else {
			return newArr[mid];
		}
	}

	public static void printArray(int[] arr) {
		for (int i = 0; i != arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
	}

	public static void main(String[] args) {
		boolean err = false;
		int testTimes = 200000;
		for (int i = 0; i != testTimes; i++) {
			int len = 30;
			int maxValue = 1000;
			int[] arr = getRandomArray(len, maxValue);
			MedianHolder medianHold = new MedianHolder();
			for (int j = 0; j != arr.length; j++) {
				medianHold.addNumber(arr[j]);
			}
			if (medianHold.getMedian() != getMedianOfArray(arr)) {
				err = true;
				printArray(arr);
				break;
			}
		}
		System.out.println(err ? "oh No" : "beautiful");

	}

}




你可能感兴趣的:(刷题)