import java.util.List; public class Sort { /** * Sorts the given list. * * @param list a list. * @pre. list != null */ public static void selection(List list) { Sort.selection(list, 0); } /** * Sorts the sublist of the given list starting at the given * index. * * @param list a list * @pre. list != null * @param begin begin index of the sublist. * @pre. begin >= 0 && begin <= list.size() - 1 */ public static void selection(List list, int begin) { if (begin >= list.size() - 1) { // do nothing } else { // find the minimum int index = Sort.minimum(list, begin); // swap elements at indices begin and index Integer temp = list.get(begin); list.set(begin, list.get(index)); list.set(index, temp); // sort the rest Sort.selection(list, begin + 1); } } /** * Returns the index of the minimum of the sublist of the given * list starting at the given index. * * @param list a list * @pre. list != null * @param begin begin index of the sublist. * @pre. begin >= 0 && begin <= list.size() - 1 */ private static int minimum(List list, int begin) { int index ; if (begin == list.size() - 1) { index = begin; } else { index = Sort.minimum(list, begin + 1); if (list.get(begin) < list.get(index)) { index = begin; } } return index; } /** * Sorts the given list. * * @param list a list. * @pre. list != null */ public static void insertion(List list) { Sort.insertion(list, 0); } /** * Sorts the sublist of the given list starting at the given * index. * * @param list a list * @pre. list != null * @param begin begin index of the sublist. * @pre. begin >= 0 && begin <= list.size() */ public static void insertion(List list, int begin) { if (begin >= list.size()) { // do nothing } else { Sort.insert(list, begin); // swap elements at indices begin and index Sort.insertion(list, begin + 1); } } /** * Insert the element at the given index in the sublist ending * at the given index so that the sublist is sorted. * * @param list a list * @pre. list != null * @param end end index of the sublist. * @pre. end >= 0 && end <= list.size() - 1 */ private static void insert(List list, int end) { if (end == 0) { // do nothing } else if (list.get(end - 1).compareTo(list.get(end)) <= 0) { // do nothing } else { // swap elements at indices end and end - 1 Integer temp = list.get(end); list.set(end, list.get(end - 1)); list.set(end - 1, temp); // insert element at index end - 1 Sort.insert(list, end - 1); } } }