Java examples for Data Structure:Sort
Returns the sorted version of the input string.
import java.awt.List; import java.util.ArrayList; import java.util.Comparator; public class Main{ public static void main(String[] argv) throws Exception{ String word = "java2s.com"; System.out.println(sort(word)); }//from w ww. j a v a 2 s . c o m /** * Returns the sorted version of the input string. The sorting is * accomplished using an insertion sort. * * @param word * -- the word to be sorted * @return the sorted result of the word */ public static String sort(String word) { String sortedWord = ""; // Create a char array out of the given word's characters char[] tempCharArray = word.toLowerCase().toCharArray(); // Copy char array to Character array for implementation of insertion // sort Character[] wordCharacters = new Character[tempCharArray.length]; for (int i = 0; i < tempCharArray.length; i++) { wordCharacters[i] = tempCharArray[i]; } // Sort characters in the word according to an insertion sort algorithm insertionSort(wordCharacters, new SortByCharacters()); // Place characters back into a String from the CharArray for (int i = 0; i < wordCharacters.length; i++) { sortedWord += wordCharacters[i]; } return sortedWord; } /** * A generic method. Sorts the input array using an insertion sort and the * input Comparator object. * * @param array * -- the input array of objects to be sorted * @param mComparator * -- the comparator to be used in the insertion sort */ public static <T> void insertionSort(T[] array, Comparator<? super T> mComparator) { int i, j; for (i = 1; i < array.length; i++) { T index = array[i]; // object to be inserted // until the insertion point is found, shift items for (j = i; j > 0 && mComparator.compare(index, array[j - 1]) < 0; j--) { array[j] = array[j - 1]; } array[j] = index; // insert object at the right point } } }