java - 这个冒泡排序算法有什么问题吗?
问题描述
我对编码很陌生,当我在大学提交过程中运行它时,我不断收到 ArrayOutofBoundsError: 8 。我不明白为什么。错误也指向交换方法,但是我什至没有写这个,因为它是骨架的一部分。仅当我尝试使用自己的冒泡排序方法时才会出现此问题。所以我认为它一定有问题。所有其他方法单独工作正常。
public void sortBubble()
{
/* This implementation uses the bubble sort algorithm. For an explanation
* of how bubblesort works, google ...
* bubblesort java
*/
// with variable subscripts ...
int i = 0; // role: stepper
if ( list[i] > list[i+1] ) swap(list[i], list[i+1]);
++i;
if ( list[i] > list[i+1] ) swap(list[i], list[i+1]);
++i;
if ( list[i] > list[i+1] ) swap(list[i], list[i+1]);
// At this point, the largest element must be in list[3].
i = 0;
if ( list[i] > list[i+1] ) swap(list[i], list[i+1]);
++i;
if ( list[i] > list[i+1] ) swap(list[i], list[i+1]);
// At this point, the second largest element must be in list[2].
i=0;
if ( list[i] > list[i+1] ) swap(list[i], list[i+1]);
// At this point, the smallest element must be in list[0].
}
解决方案
为什么不使用循环?这就足够了。
for (int i = 0; i < ( n - 1 ); i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] < array[j+1]) /* For ascending order use > */
{
int swap = array[j];
array[j] = array[j+1];
array[j+1] = swap;
}
}
}
示例代码:
import java.util.Scanner;
class Demo {
public static void main(String []args) {
int n = 3; // Number of elements
Scanner in = new Scanner(System.in);
int array[] = new int[n];
System.out.println("Enter " + n + " integers");
for (int i = 0; i < n; i++)
array[i] = in.nextInt();
// Sorting in descending order
for (int i = 0; i < ( n - 1 ); i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] < array[j+1]) /* For ascending order use ">" */
{
int swap = array[j];
array[j] = array[j+1];
array[j+1] = swap;
}
}
}
// Display the sorted list
System.out.println("Sorted list of numbers:");
for (int i = 0; i < n; i++)
System.out.println(array[i]);
}
}
推荐阅读
- node.js - 通过 expressjs 下载的文件全部损坏
- google-bigquery - 在 BigQuery 架构中定义数组
- elasticsearch - Elasticsearch:多个字段,如果存在则返回true
- git - 如何在我的本地机器上配置 Git?
- mysql - 如何排除表之间一对多关系中的行(SQL查询)
- excel - 在另一个单元格中有特定值时计数单元格
- java - 使用 Spring 属性加载而不初始化 Spring 上下文
- javascript - JavaScript - 使用 data-pic 添加 img
- python - 如何预测,模型需要多少 epochs?
- activemq - 如何向 AMQP 消费者 Artemis 推送消息