- /**
- * 排序算法学习之希尔排序
- * 实现方法:
- * 希尔排序是特殊的插入排序
- * 插入排序按照处理的子数组长度递增分为多趟插入操作
- * 而每一趟插入操作处理的子数组元素索引间隔都是1(即步长)
- * 希尔排序每趟处理的子数组元素索引间隔是动态的。
- */
- package 排序算法.shellSort;
- public class ShellSort {
- /**
- * 对输入数组进行希尔排序
- * @param a 待排序数组,索引有效范围从0开始
- */
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public static void shellSort(Comparable[] a) {
- int incr = a.length / 2;//初始步长
- while (incr >= 1) {
- for (int i = incr; i < a.length; i++) {
- Comparable insertElement = a[i];
- int j;
- for (j = i - incr; j >= 0 &&
- insertElement.compareTo(a[j]) < 0; j -= incr)
- a[j + incr] = a[j];
- a[j + incr] = insertElement;
- }
- if (incr == 2)
- incr = 1;
- else
- incr = (int) (incr / 2.2);
- }
- }
- }
- /**
- * 排序算法学习之选择排序
- * 实现方法:
- * 每次选择子数组中最大的元素依次排列在子数组末尾,
- * 子数组的长度依次递减。
- */
- package 排序算法.selectionSort;
- public class SelectionSort {
- @SuppressWarnings({ "rawtypes", "unchecked" })
- /**
- * 查找指定长度的数组中最大元素的索引
- * @param a 指定数组
- * @param n 数组长度
- * @return 最大元素的索引
- */
- public static int max(Comparable[] a, int n) {
- if (n < 0)
- throw new IllegalArgumentException("数组为空");
- int positionOfCurrentMax = 0;
- for (int i = 1; i <= n; i++)
- if (a[positionOfCurrentMax].compareTo(a[i]) < 0)
- positionOfCurrentMax = i;
- return positionOfCurrentMax;
- }
- /**
- * 交换指定数组中指定索引的元素
- * @param a 指定数组
- * @param i 第一个索引
- * @param j 第二个索引
- */
- public static void swap(Object[] a, int i, int j) {
- Object temp = a[i];
- a[i] = a[j];
- a[j] = temp;
- }
- /**
- * 对输入数组执行一般选择排序
- * @param a 输入数组
- */
- @SuppressWarnings("rawtypes")
- public void selectionSort(Comparable[] a) {
- //按照子数组长度递减的顺序进行每趟的选择操作
- for (int size = a.length; size > 1; size--) {
- int j = max(a, size - 1);
- swap(a, j, size - 1);
- }
- }
- /**
- * 对输入数组执行早结束版本的选择排序
- * @param a 输入数组,数组索引有效范围从0开始
- */
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public void selectionSort2(Comparable[] a) {
- boolean sorted = false;//当前子数组是否有序的标志
- for (int size = a.length; !sorted && (size > 1); size--) {
- int pos = 0;
- sorted = true;
- for (int i = 1; i < size; i++)
- if (a[pos].compareTo(a[i]) <= 0)
- pos = i;
- else