import java.util.ArrayList;
public class BubbleSort {
// the sort method takes in an ArrayList of Strings, sorts
// them in ascending number of characters, and returns a new
// ArrayList of Strings which is already sorted. This method
// does NOT modify the original ArrayList passed in.
public ArrayList<String> sort(ArrayList<String> a){
ArrayList<String> sortingList = new ArrayList<String>();
sortingList = a;
String test = "";
String test2 = "";
int length = 0;
int length2 = 0;
for(int j =0; j<a.size(); j++){
for (int i =0; i<sortingList.size()-1; i++){
test = a.get(i);
test2 = a.get(i+1);
length = test.length();
length2 = test2.length();
if(length2<length){
sortingList.set(i,test2);
sortingList.set(i+1,test);
}
}
}
return sortingList;
}
}
==================================主要方法=============== =======================
import java.util.ArrayList;
import java.util.Scanner;
public class BubbleSortTest {
public static void main(String[] args) {
ArrayList<String> inputs = new ArrayList<String>();
// get inputs from user
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of Strings to enter: ");
int no = sc.nextInt();
sc.nextLine(); // clears buffer in Scanner
for (int i = 0; i < no; i++){
System.out.print("Enter String number " + i + ": ");
inputs.add(sc.nextLine()); // add input into ArrayList
}
// invoke the sort method to see if it works
BubbleSort bs = new BubbleSort();
ArrayList<String> sortedInputs = bs.sort(inputs);
// print out the Strings in sortedInputs
System.out.println("Sorted sequence:");
for (int i = 0; i < sortedInputs.size(); i++){
System.out.println(sortedInputs.get(i));
}
// print out the Strings in the original inputs
System.out.println("Original sequence:");
for (int i = 0; i < inputs.size(); i++){
System.out.println(inputs.get(i));
}
}
}
输入示例
121234256464534
1123123
123141243124124
123
我的排序顺序和原始顺序都按升序修改,即使我创建了一个要返回的新数组列表,同时确保我没有对原始数组进行任何更改。
提前致谢