Java中的双向冒泡排序?
我需要在我的代码中实现双向冒泡排序。
换句话说,in
将从左到右首先携带最大值。
但当它到达out
时,它应该反转并从右向左携带最小值。
建议我在当前索引之外再实现另一个out
索引。
这就是我到目前为止所拥有的——只有 2 个循环。我想我必须以某种方式将它们结合起来?
public void bubbleSort() {
int out, in; // nElems in my case is 4, because I have 4 elements in my array
for(out=nElems-1; out>1; out--) // outer loop backward
for(in=out; in>1; in--) // inner loop backward
if(a[in] < a[in-1])
swap(in, in-1);
for(out=0; out<nElems; out++) // outer loop forward
for(in=0; in<out; in++) // inner loop forward
if(a[in] > a[in+1])
swap(in, in+1);
I need to implement the bidirectional bubble sort in my code.
In other words in
will go from left to right first carrying the largest value.
But when it reaches out
, it should reverse and go from right to left carrying the smallest value.
I am advised to to implement another out
index in addition the current one.
This is what I have so far - just 2 loops. I am guessing I have to combine them somehow?
public void bubbleSort() {
int out, in; // nElems in my case is 4, because I have 4 elements in my array
for(out=nElems-1; out>1; out--) // outer loop backward
for(in=out; in>1; in--) // inner loop backward
if(a[in] < a[in-1])
swap(in, in-1);
for(out=0; out<nElems; out++) // outer loop forward
for(in=0; in<out; in++) // inner loop forward
if(a[in] > a[in+1])
swap(in, in+1);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我建议您将该方法拆分为您可以理解的块,例如:
并测试它:
输出:
I recommend you split the method up for chunks that you can comprehend, like:
And to test it:
Output:
仅使用2个循环的双向冒泡排序 2 个索引变量。
Bidirectional Bubble Sort using only 2 loops & 2 index variables.
双向冒泡排序,排序变量:array[]
在 10_000 个随机选择的元素上,标准冒泡排序在 410ms 内完成,双向冒泡排序在 319ms 内完成
Bidirectional bubble sort, sorting variable: array[]
On 10_000 randomly selected elements, standard bubble sorts completes in 410ms and bidirectional bubble sort in 319ms