我正在尝试进行鸡尾酒式排序,但是我在行if (a[i] > a[i + 1])
上遇到了异常,我不确定为什么。
这是完整的代码。抱歉,这是完全错误的。
import java.util.Arrays;
import java.util.Scanner;
public class Cocktail
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int count = 0;
boolean switched = true;
int[]a = new int[10];
for (int i = 0; i < a.length; i++)
{
int value = input.nextInt();
a[i] = value;
}
System.out.println(a[0]);
while (switched == true)
{
switched = false;
for (int i = 0; i < a.length; i++)
{
if (a[i] > a[i + 1])
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
for (int i = a.length; i >= 0; i++)
{
if (a[i] > a[i + 1])
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
if (switched == false)
{
System.out.println(count);
}
}
}
}
答案 0 :(得分:1)
您需要更改
if (a[i] > a[i + 1])
像这样-> if (i < a.length-1 && a[i] > a[i + 1])
。
问题在于它试图到达第11个元素;)
如果可以的话,这是代码的编辑版本:
Scanner input = new Scanner(System.in);
int count = 0;
boolean switched = true;
int[]a = new int[10];
System.out.println("enter 10 Integers: ");// # Added to make code clearer
for (int i = 0; i < a.length; i++)
{
int value = input.nextInt();
a[i] = value;
}
System.out.println("thankyou, Sorting now!");//# also this one
while(switched == true)
{
switched = false;
for (int i = 0; i < a.length; i++)
{
if (i < a.length-1 && a[i] > a[i + 1]) // <-- # here was the problem
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
for (int i = a.length; i >= 0; i++)
{
if (i < a.length-1 && a[i] > a[i + 1]) //<-- # Also Here
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
if (switched == false)
{
System.out.println("count is "+ count);
}
}
// # added part to print array for testing
System.out.println("Sorted Array:");
for (int i = 0; i <a.length ; i++) {
System.out.print(a[i]+", ");
}
}//main
}//class
以下是输出:
复制并粘贴,Run and Happy Coding = D