Here you can find the source of sort(final List
Parameter | Description |
---|---|
list | String list containing the elements to be sorted. Can be <code>null</code>. |
null
if null
was passed in.
public static List<String> sort(final List<String> list)
//package com.java2s; import java.util.ArrayList; import java.util.List; import java.util.Set; public class Main { /**/* w w w . j a v a 2s. com*/ * Sorts the specified string list. O(N) is n log(n). * * @param list String list containing the elements to be sorted. Can be <code>null</code>. * * @return Sorted string list or <code>null</code> if <code>null</code> was passed in. */ public static List<String> sort(final List<String> list) { List<String> listSorted = null; if (list != null) { listSorted = new ArrayList<String>(); for (final String str : list) { listSorted.add(getIndexForSortedInsert(listSorted, str), str); } } return listSorted; } /** * Sorts the specified string list. O(N) is n log(n). * * @param set String set containing the elements to be sorted. Can be * <code>null</code>. * * @return Sorted string list or <code>null</code> if <code>null</code> was * passed in. */ public static List<String> sort(final Set<String> set) { List<String> listSorted = null; if (set != null) { listSorted = new ArrayList<String>(); for (final String str : set) { listSorted.add(getIndexForSortedInsert(listSorted, str), str); } } return listSorted; } /** * Determines for a sorted list and an object, what index the string * could be inserted. Note: This method just returns the index, but does not * insert the string. * * @param listSorted * Sorted string list. Can be <code>null</code>. * @param item * String to be inserted. Can be <code>null</code>. * * @return Index for string insertion. */ private static int getIndexForSortedInsert(final List<String> listSorted, final String item) { if (listSorted == null || item == null) { return 0; } int low = 0; int high = listSorted.size() - 1; while (low <= high) { final int mid = (low + high) >>> 1; final String midVal = listSorted.get(mid); final int cmp = midVal.compareToIgnoreCase(item); if (cmp < 0) { low = mid + 1; } else if (cmp > 0) { high = mid - 1; } else { return mid; // key found } } return low; // key not found. } }