[英]Bubble Sorting Explanation
I am writing a bubble code program for my intro to Java class, and it is a very simple assignment. 我正在为我的Java类简介编写一个泡泡代码程序,这是一个非常简单的任务。 I am just curious as to if my code is correct.
我只是好奇我的代码是否正确。 The thing is, my code works, but it is different from the normal solution I have seen other people post.
问题是,我的代码有效,但它与我见过的其他人发布的常规解决方案不同。 I am not sure if I have just done a different sorting method, or if I have just written a different version of bubble sorting.
我不确定我是否刚刚完成了不同的排序方法,或者我刚刚编写了不同版本的冒泡排序。
So below is the code I have written: 以下是我写的代码:
import java.util.Arrays;
import java.util.Random;
public class BubbleSort
{
public static void main(String[] args)
{
Random ran = new Random();
int[] list = new int[10];
for(int i = 0; i < list.length; i++)
list[i] = ran.nextInt(50);
System.out.println(Arrays.toString(list));
System.out.println(Arrays.toString(bubbleSort(list)));
}
public static int[] bubbleSort(int[] list)
{
int temp;
for(int i = 0; i < list.length; i++)
{
for(int j = 0; j < list.length - 1; j++)
{
if(list[j] > list[j + 1])
{
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
return list;
}
}
And that works perfectly fine. 这完全没问题。 But I am not sure if it is actually 'bubble sorting'.
但我不确定它是否实际上是“泡沫分类”。
Most people have this in their for loop
when they are writing this same program 大多数人在编写同一个程序时都会在
for loop
使用它
for(int j = 0; j < list.length - 1 - i; i++)
The question I have is what is the point of doing the list.length - 1- i
whenever what I have, list.length - 1
works perfectly fine? 我的问题是如何做
list.length - 1- i
每当我有, list.length - 1
工作得很好?
Have I accidentally done a different form of sorting? 我是否意外地做了不同的排序形式? They both work I am just curious as to why people do
list.length - 1 - i
他们都工作我只是好奇为什么人们做
list.length - 1 - i
@markspace gave me the correct answer in the comments so all credit to him. @markspace在评论中给了我正确答案,所以都归功于他。
I will just post this for the sake of proving his answer. 我将发布这篇文章是为了证明他的答案。 I tested my code with 10,000 integers and created a timer to see how long it takes.
我用10,000个整数测试了我的代码并创建了一个计时器来查看它需要多长时间。 Whenever I used my code which just had
j < list.length - 1
sorting 10,000 integers took 297 milliseconds on average. 每当我使用我的代码时,只有
j < list.length - 1
排序10,000个整数平均需要297毫秒。 Once I changed my for loop to have j < list.length - 1 - i
it sorted the loop about 35% faster at just 196 milliseconds. 一旦我改变了我的for循环以使
j < list.length - 1 - i
它将循环分类的速度提高了约35%,仅为196毫秒。 As stated by mark, adding the - i
just prevents the program from re-checking the last elements which are already sorted thus saving time. 如标记所述,添加
- i
只是阻止程序重新检查已经排序的最后元素,从而节省时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.