集册 Java实例教程 返回输入字符串的排序版本。

返回输入字符串的排序版本。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

518
返回输入字符串的排序版本。


import java.awt.List;

import java.util.ArrayList;
/* 
*来 自
 时 代 J a v a - nowjava.com
*/

import java.util.Comparator;


public class Main{

    public static void main(String[] argv) throws Exception{

        String word = "nowjava.com";

        System.out.println(sort(word));

    }

    /**

     * 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];
        /** from 
        NowJava.com - 时代Java**/

        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
展开阅读全文