我设法翻译鸡尾酒排序方法的伪代码,但是当我运行它时,我收到运行时错误显示:
java.lang.ArrayIndexOutOfBoundsException: 1
at Sorting.cocktailSort(Sorting.java:119)
at Sorting.plotCocktailSortTest(Sorting.java:213)
at Sorting.main(Sorting.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
以下是此排序方法的代码:
public static int cocktailSort(String[] numbers) {
String [] inputCocktail = new String [numbers.length];
for(int a = 0; a < numbers.length-2; a++) {
inputCocktail[a] = numbers [a];
}
int left = 0;
int right = numbers.length;
boolean swapped =true;
String temp = "";
int counter = 0;
while (left < right && swapped) {
swapped =false;
for (int mid = 0; mid < numbers.length; mid++) {
if ((inputCocktail[mid].compareTo(inputCocktail[mid+1]))>0)
{ temp = inputCocktail[mid];
inputCocktail[mid] = inputCocktail[mid+1];
inputCocktail[mid+1] = temp;
swapped = true;
}
}
right--;
if (swapped){
swapped = false;
for(int mid = numbers.length-2; mid>0; mid--)
if ((inputCocktail[mid].compareTo(inputCocktail[mid-1]))<0)
{ temp = inputCocktail[mid];
inputCocktail[mid]= inputCocktail[mid-1];
inputCocktail[mid-1] = temp;
swapped = true;
}
}
}
left++;
counter++;
return counter;
}
无论我查看我的代码多少次,我都无法找到错误。 任何帮助,将不胜感激。感谢。
编辑: 第一种比较字符串的方法:
public static int compare(String a, String b)
{
int compared = 0;
a = a.toLowerCase();
b = b.toLowerCase();
//program assumes strings are equal
for (int i = 0; i<a.length() && i<a.length(); i++){
//for() loop goes on until the largest string
int c = a.charAt(i);
int d = b.charAt(i);
//convert char into int for comparison just in case
if(c < d){
compared = -1;
break;
//breaks at the first occurence of non equal characters
}
else if(c > d){
compared = 1;
break;
//same as above
}
}
return compared;
}
编辑#2:
public static void plotCocktailSortTest(int N_MAX) {
int[] cocktail_sort_results = new int[N_MAX];
// test sorting for arrays from size 1 to N_MAX
// MAKE SURE THAT YOUR METHOD IS ACTUALLY SORTING THE TEST ARRAY!!!!!!
for (int i = 1; i < N_MAX; i++) {
String[] test_array = ArrayUtilities.getRandomNamesArray(i);
cocktail_sort_results[i] = cocktailSort(test_array);
}
// create a plot window
PlotWindow pw = new PlotWindow("Cocktail Sort!");
// add a plot to the window using our results array
pw.addPlot("CocktailSort", cocktail_sort_results);
}
答案 0 :(得分:2)
这看起来不对
for (int mid = 0; mid < numbers.length; mid++) {
if ((inputCocktail[mid].compareTo(inputCocktail[mid+1]))>0)
如前所述,您只使用inputCocktail
numbers.length - 2
基于您新发布的代码
for (int i = 1; i < N_MAX; i++) {
String[] test_array = ArrayUtilities.getRandomNamesArray(i);
我不知道ArrayUtilities
是什么,但也许getRandomNamesArray(1)
会返回一个大小为1
的数组
在以后的代码中,您尝试访问基于size - 2
和size + 1
的数组,这显然会失败。