堆排序数组

编程入门 行业动态 更新时间:2024-10-18 01:38:36
本文介绍了堆排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

谁能给我解释一下它究竟是如何工作的code的下一个序列。

的PriorityQueue<整数GT; pQueue =新的PriorityQueue<整数GT;(); 对于(INT W:X){     pQueue.add(重量); } 对于(INT K = 0; K< x.length; k ++){     X [k]的= pQueue.poll(); } //输出数组 的System.out.println(\\ nHere是有序阵列堆排序:); 对于(INT W:X){     System.out.print(W +); }

解决方案

的PriorityQueue<整数GT; pQueue =新的PriorityQueue<整数GT;();

这行创建整数的优先级队列。优先级队列存储的整理的项目(在你的案件整数)的列表。

当您添加一个int到pQueue,这是地方在正确的位置的值。

例如,如果我在这个顺序添加数字1,10和5到优先级队列,这样的事情会发生:

pqueue = {} //在启动空pqueue = {1} // 1加pqueue = {1→10} // 10加入pqueue = {1→5→10} // 5加入

的通知5被放置方式1到10之间。

当你调用 pQueue.poll(); 返回pQueue的第一个元素是保证是队列内的最小值。 (该值是从该队列在此过程中去除)。

重复调用将在顺序1,5,10中的示例返回的数字上述

由于这是你的数组被排序。

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("\nHere is the sorted array with HeapSort:"); for (int w : x) { System.out.print(w + " "); }

解决方案

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.

更多推荐

堆排序数组

本文发布于:2023-11-30 09:28:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649501.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!