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;
}
}
=================================MAIN METHOD=====================================
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));
}
}
}
input example
121234256464534
1123123
123141243124124
123
my sorting sequence & original sequence are both amended in ascending sequence even though I created a new arraylist to return while ensuring I did not make any changes to the original one.
Thanks in advance