Home Java Java-tips Data Strings 96string_examples Java: Example - String sort

Ask Questions?

View Latest Questions

Advertisement


 
 

Java: Example - String sort
Posted on: March 3, 2008 at 12:00 AM
Java: Example - String sort

Java: Example - String sort

Sorting is a mechanism in which we sort the data in some order. There are so many sorting algorithm are present to sort the string. The example given below is based on Selection Sort. The Selection sort algorithm finds the minimum and swap it from the first position. And in the next step it leaves the first value and searches the minimum value from the rest of the values. If it finds then it swaps with the current value and then moves next and so on.

//-------------------------------------------------- sort()
// Sort a String array using selection sort.
void sort(String[] a) {
  for (int i=0; i<a.length-1; i++) {
     for (int j=i+1; j<a.length; j++) {
        if (a[i].compareTo(a[j]) > 0) {
           String temp=a[j]; a[j]=a[i]; a[i]=temp;
        }
     }
  }
}
Copyleft 2003 Fred Swartz MIT License, Last update: 2003-10-29
Advertisement


DMCA.com