1. Member
Join Date
Nov 2007
Posts
13
Rep Power
0

## how to sort

what is the way to sort alphabetically strings from an array?

(for example lets say we have the strings "Apple", "Key" and "Zebra" in an array of 5 elements.)

2. ## Sorting Strings

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.
Java Code:
```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();
}
}```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•