Selection sort the remaining N-1 items (without touching the front item).
findSmallest()
Since < can't compare strings, we could use the compareTo method.
public class Sort {
/** Sorts strings destructively. */
public static void sort(String[] x) {
// find the smallest item
// move it to the front
// selection sort the rest (using recursion?)
}
/** Returns the smallest string in x. */
public static String findSmallest(String[] x) {
String smallest = x[0];
for (int i = 0; i < x.length; i += 1) {
int cmp = x[i].compareTo(smallest);
if (cmp < 0) {
smallest = x[i];
}
}
return smallest;
}
}
public static void swap(String[] x, int a, int b) {
String temp = x[a];
x[a] = x[b];
x[b] = temp;
}
public static void testSwap() {
String[] input = {"i", "have", "an", "egg"};
int a = 0;
int b = 2;
String[] expected = {"an", "have", "i", "egg"};
Sort.swap(input, a, b);
org.junit.Assert.assertArrayEquals(expected, input);
}
Recursive Array Helper Method
Since Java doesn't support array slicing (x[1:2]), we should add a helper method to recursively sort the whole array.
public static void sort(String[] x) {
sort(x, 0);
}
public static void sort(String[] x, int start) {
smallestIndex = findSmallest(x);
swap(x, start, smallestIndex);
sort(x, start + 1);
}
However, the findSmallest method doesn't work well since it will start from 0 instead of the start point. We could easily fix it.
public static int findSmallest(String[] x, int start) {
int smallestIndex = start;
for (int i = start; i < x.length; i += 1) {
int cmp = x[i].compareTo(x[smallestIndex]);
if (cmp < 0) {
smallestIndex = i;
}
}
return smallestIndex;
}
Enhanced JUnit Test
To allow IntelliJ to automatically run the tests, we could modify our test structure as the following rules: