chap11介绍了一些排序算法。简化起见,仅对int数组的元素进行排序,排除泛型、排序码、链表实现等等分散(学习排序)精力的因素。
在学习编程时,要记住:编程的核心技术有二:
★程序的组织(面向对象技术)、问题求解(算法)。(page11,0.1.5问题求解)
学习OO,如同使用望远镜;
学习算法,如同使用显微镜。
所以,同学们要学会非常灵活地上蹿下跳。其实,本章最重要的目标是希望同学们在学习系列排序算法时,将它们加以组织。
本章将介绍 各种排序算法,它们都将完成同一个功能:int[] sort(int[] arr),排序的目标是将数组的元素按照 非降序排列,即前面的数小于或等于后面的数。
为了测试方便,(一个 策略模式的应用),各种排序算法被设计成抽象类 algorithm.sorting.IntSort的子类。
注意:书上的测试代码
你可以使用依赖注入工具如 IoC容器 tool.God,通过配置文件来改善Test。
本章将介绍 各种排序算法,它们都将完成同一个功能:int[] sort(int[] arr),排序的目标是将数组的元素按照 非降序排列,即前面的数小于或等于后面的数。
为了测试方便,(一个 策略模式的应用),各种排序算法被设计成抽象类 algorithm.sorting.IntSort的子类。
package algorithm.sorting;
public abstract class IntSort{
public abstract int[] sort(int[] arr);
/**
* Swaps arr[one] with arr[two].换位
*/
public static void swap(int[] arr ,int one, int two){
if(one == two){return;}
int temp = arr [one];
arr [one] = arr [two];
arr [two] = temp;
}
}
注意:书上的测试代码
package algorithm.sorting;
/**
* Test.java.
* 测试排序实现的正确性、性能.
* @author yqj2065
* @version 0.1
*/
public class Test{
private static IntSort s = new SelectionSort();//排序算法LatchMergeSort
/**
* 基本测试。对指定长度size的数组,初始化为0~size,乱序。
*/
public static void basicTest(int size){
//略
}
}
有静态域 static IntSort s = new SelectionSort();
需要测试其他排序算法如HeapSort时,需要修改源代码,如使s = new HeapSort ()。你可以使用依赖注入工具如 IoC容器 tool.God,通过配置文件来改善Test。
package algorithm.sorting;
import tips.God;
public class Test{
private static IntSort s =(IntSort) God.create("11-0"); //
这样Test仅仅依赖于抽象类algorithm.sorting.IntSort。