编写程序,接受用户输入的若干字符串,并按字典排序输出。要求使用两种以上的排序算法。

2024-12-04 14:10:36
推荐回答(2个)
回答1:

import java.util.ArrayList;
import java.util.Iterator;

public class CompareString {
public void countingSort(String[] A,char[] B,int k) { //计数排序
String[] temp = new String[A.length+1];
int[] c = new int[k+1];
int i,j;
for(i = 0; i <= k; i++)
c[i] = 0;
for(j = 0; j < B.length; j++) {
c[B[j]-'a'] = c[B[j]-'a'] + 1;
}
for(i = 1; i <= k; i++)
c[i] = c[i] + c[i-1];

for(j = A.length - 1; j >= 0; j--) {
temp[c[B[j]-'a']] = A[j];
c[B[j]-'a'] = c[B[j]-'a'] - 1;
}

for(i = 1; i <= A.length; i++) {
A[i-1] = temp[i];
}
}

public void radixSort(String[] A,int d) {
ArrayList[] arr = new ArrayList[26];
countingSort(A,divide(A,d),max(divide(A,d))-'a');
for(int i = 0; i < A.length; i++) {
int temp = A[i].charAt(d-1)-'a';
if(arr[temp] == null)
arr[temp] = new ArrayList();
arr[temp].add(A[i]);
}
for(int j = 0; j < 26; j++) { //对各个桶进行插入排序
if(arr[j] != null) {
insert(arr[j]);
}
}

//将各个桶结果进行合并
int count = 0;
for(int i = 0; i < 26; i++) {
if(arr[i] != null) {
Iterator it = arr[i].iterator();
while(it.hasNext()) {
String temp = (String)it.next();
A[count] = temp;
count++;
}

}
}
}

public void insert(ArrayList list) { //插入排序
if(list.size() > 1) {
for(int i = 1; i < list.size() ; i++) {
if(compareTo((String)list.get(i),(String)list.get(i-1))< 0) {
String temp = (String)list.get(i);
int j = i -1;
for(; j >= 0 && compareTo(temp,(String)list.get(j))< 0;j-- )
list.set(j + 1, list.get(j));
list.set(j + 1, temp);
}
}
}

}

int compareTo(String a, String b) { //比较两个字符串的大小
return a.compareTo(b);
}
public char[] divide(String[] A, int count) { //取数组中每个字符串的第d个字符
char[] B = new char[A.length];
for(int i = 0; i < A.length; i++) {
B[i] = A[i].charAt(count-1);
}
return B;
}

public char max(char[] B) { //求数组当中的最大值
char max = 'a';
for(int i = 0 ; i < B.length; i++) {
if(B[i] > max) max = B[i];
}
return max;
}
public static void main(String[] args) {
CompareString cs = new CompareString();
String[] A = {"apple","hello","dear","clear","day","happy"};
cs.radixSort(A,1);
for(int i = 0; i < A.length;i++)
System.out.print(A[i] + " ");

}

}

回答2:

将使用的所有字符串使用Arrays.sort();进行排序即可 简便易用
或者如下字符串 这样进行字典排序:
package work1;

import java.util.*;

public class Name {
public static void main(String[] arguments){
String names[] = {"Lauren","Audrina","Heidi","Whitney",
"Stephanie","Spencer","Lisa","Brody","Frankie",
"Holly","Jordan","Brian","Jason"};
System.out.println("The orignal order:");
for (int i = 0; i < names.length; i++) {
System.out.print(i + ": " + names[i] + " ");
}
Arrays.sort(names);
System.out.println("\nThe new order:");
for (int i = 0; i < names.length; i++) {
System.out.print(i + ": " + names[i] + " ");
}
System.out.println();
}

}