[英]Sorting an array of string data using the insertion sort method
我在使用插入對字符串數組進行排序時遇到問題。
當我編譯以下代碼時:
public class Project1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String names[]=new String[5];
int size=names.length;
System.out.println("Enter the 5 car manufacturers: ");
//Load Array
for (int i = 0; i < 5; i++) {
names[i] = input.nextLine();
}
//Print descending order list
String[] descSort;
descSort=bubbleSortDesc(names);
System.out.println("Car manufacturers listed sorted in descending order (via BubbleSort): ");
for (int x=0; x < names.length; x++) {
System.out.println(names[x]);
}
//Print ascending order list
insertionSortAsc(names, size);
System.out.println("Car manufacturers listed sorted in ascending order (via InsertionSort): ");
for (int z=0; z < names.length; z++) {
System.out.println(names[z]);
}
}¨
public static String[] bubbleSortDesc(String[] names) {
String temp;
int passNum, i, result;
for (passNum=1; passNum <= 4; passNum++) {
for (i = 0; i<=(4-passNum); i++) {
result=names[i].compareToIgnoreCase(names[i+1]);
if(result<0) {
temp=names[i];
names[i]=names[i+1];
names[i+1]=temp;
}
}
}
return names;
}
public static void insertionSortAsc(String[] names, int i) {
String temp = names[i];
int j = i-1;
while (j >= 0 && names[j].compareToIgnoreCase(temp) > 0) {
names[j+1]=names[j];
j--;
}
names[j+1]=temp;
}
public static void insertionSort(String[] names, int n) {
for(int i = 1; i<n; i++) {
insertionSortAsc(names, i);
}
}
}
它給了我錯誤:
cannot find symbol- method insert(java.lang.String[], int)
我懷疑這與我們被告知使用我們的書作為代碼參考這一事實有關,但該書僅涉及對 int 類型的數據進行排序,並且沒有對字符串數據進行排序的示例。
任何幫助表示贊賞。
編輯:修復錯誤后,程序編譯並執行,但在輸入數據后崩潰並給我以下錯誤
java.lang.ArrayIndexOutofBoundsException:
5
此錯誤突出顯示行String temp = names[i]
您尚未定義名為 insert 的方法。
這將按照您的預期工作:
public static void insertionSortAsc(String[] names, int n)
{
for(int i = 1; i<n; i++)
{
insert(names, i);
}
}
public static void insert(String[] names, int i)
{
String temp = names[i];
int j = i - 1;
while (j >= 0 && names[j].compareToIgnoreCase(temp) > 0)
{
names[j + 1]= names[j];
j--;
}
names[j + 1] = temp;
}
public static void insertionSort(int... arr) {
for (int i = 1; i < arr.length; i++) {
if (arr[i] >= arr[i - 1])
continue;
int j = i - 1;
for (; j >= 0; j--)
if (arr[j] < arr[i])
break;
int tmp = arr[i];
System.arraycopy(arr, j + 1, arr, j + 2, i - j - 1);
arr[j + 1] = tmp;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.