Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

java - Heap Sort array

Who can explain to me exactly how it works next sequence of code.

 PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();       
 for (int w : x) {
     pQueue.add(w);
 }
 for (int k = 0; k < x.length; k++) {
     x[k] = pQueue.poll();
 }

 // Print the array
 System.out.println("
Here is the sorted array with HeapSort:");
 for (int w : x) {
     System.out.print(w + "  ");   
 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();     

This line creates a priority queue of Integers. A priority queue stores a "sorted" list of items (in your case Integers).

When you add an int to pQueue ,it is places the value in the correct position.

E.g if I add numbers 1, 10 and 5 in this order to a priority Queue, something like this will happen:

pqueue = {}          //empty at start
pqueue = {1}         //1 added
pqueue = {1->10}     //10 added
pqueue = {1->5->10} // 5 added

notice how 5 gets placed between 1 and 10.

When you call pQueue.poll(); the first element of pQueue is returned which is guaranteed to be the smallest value inside the queue. (The value is removed from the queue during this process).

Repeated calls would return the numbers in the example above in the order 1 , 5, 10.

Due to this your array gets sorted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...