String implements the Comparable interface so we can use the
compareTo method for sorting. See first paragraph and "Classes Implementing Comparable" table at
Object Ordering for bird's–eye view.
public class Sorting {
public static void main(String[] args) {
String[] array = { "five", "Apple", "Zebra", "Key", "elements" };
sort(array);
print(array);
sortIgnoreCase(array);
print(array);
}
private static void sort(String[] strs) {
for(int j = 0; j < strs.length; j++) {
String minValue = strs[j];
int minIndex = j;
for(int k = j+1; k < strs.length; k++) {
if(strs[k].compareTo(minValue) < 1) {
minValue = strs[k];
minIndex = k;
}
}
if(minIndex != j) {
// found a lower value - swap elements
String temp = strs[j];
strs[j] = minValue;
strs[minIndex] = temp;
}
}
}
private static void sortIgnoreCase(String[] strs) {
for(int j = 0; j < strs.length; j++) {
String minValue = strs[j].toLowerCase();
int minIndex = j;
for(int k = j+1; k < strs.length; k++) {
if(strs[k].toLowerCase().compareTo(minValue) < 1) {
minValue = strs[k].toLowerCase();
minIndex = k;
}
}
if(minIndex != j) {
// found a lower value - swap elements
String temp = strs[j];
strs[j] = minValue;
strs[minIndex] = temp;
}
}
}
private static void print(String[] strs) {
for(int j = 0; j < strs.length; j++) {
System.out.print(strs[j]);
if(j < strs.length-1)
System.out.print(", ");
}
System.out.println();
}
}