I am in high school and am taking an AP computer programming class (Java). In my course I have to create a void method that sorts an array that is passed in. It must be void (requirement) and needs to modify the variable passed into it (requirement). I have to use the runner code they provided. I am fairly new to coding and still a little confused by what the language can and cannot do. The sorting works, but I can't see how to modify the passed in variable of the main method.
public class InsertionSort extends Sort {
public <T extends Comparable<T>> void sortList(ArrayList<T> arr) {
ArrayList<T> arr2 = new ArrayList<T>(arr.size());
for (int i = 0; i < arr.size(); i++) {
boolean done = false;
int insertIndex = 0;
int k = i;
T next = arr.get(i);
while (k>0 && insertIndex == 0) {
if (next.compareTo(arr2.get(k-1)) > 0) {
// System.out.println("if i" + i + " k" + k);
insertIndex = k;
done = true;
}
k--;
}
arr2.add(insertIndex, arr.get(i));
}
//System.arraycopy(arr2,0,arr,0,arr2.size());
arr = arr2; //<--my attempt to alter runner variable
//System.out.println(" arr 2 = " + arr2);
//System.out.println(" arr 1 = " + arr);
}
}
// Runner
public static void main( String[] args )
{
ArrayList<String> s = new ArrayList<String>();
String[] sArr = { "you", "can", "observe", "a", "lot", "just", "by", "watching" };
for ( String x : sArr ) { s.add( x ); }
Sort ss = new InsertionSort();
ss.sortList( s );
System.out.println( s );
}
I basically need to modify the ArrayList(s) when calling the sortList() method (that is sorted) and then print from the calls to System.out.println().
The sort works but "s" will not change and I don't know where to begin to fix it. The caller is completely set in stone (class requirement), and the class and method headers must remain the same (for the same reason).
I might be missing a "{" or "}" from the copy and pasting.