正文之前
寫了好幾篇排序算法的文章,剛好碰上課程作業,需要比較一種慢排序和一種快排序的效率,所以《排序》系列文章中間就安排了這個小插曲,本文選取的排序方式為選擇排序和歸并排序
正文
本文將介紹以下內容:
- 計算運行時間
- 比較二者運行時間
- 根據運行時間作圖
筆者所使用的書籍為《算法(第四版)》,所以有涉及到書籍中的API(StdRandom, Stopwatch, StdDraw)
1. 計算運行時間
歸并排序
public static double timeTrial1(int N){
int [] a = new int [N];
for (int i = 0; i < N; i++) {
a[i] = StdRandom.uniform(N);
}
Stopwatch timer = new Stopwatch();
MergeSort.sort(a);
return timer.elapsedTime();
}
創建Stopwatch對象時開始及時,elapsedTime()方法返回自從創建對象到返回值之間所經過的時間(也就是排序運行的時間),單位為 s(秒)
選擇排序
public static double timeTrial2(int N){
double[] a = new double[N];
for (int i = 0; i < N; i++) {
a[i] = StdRandom.uniform(N);
}
Stopwatch timer = new Stopwatch();
SelectionSort.sort(a);
return timer.elapsedTime();
}
采用的方法和上述相同
2. 比較二者運行時間
寫一個測試數據(數據大小從200到204800),得出運行時間:
為了表示歸并排序究竟比選擇排序快多少,在for循環中加一行代碼:
System.out.printf("\t\tMergeSort is %f times faster than SelectionSort\n",time2/time1);
數據量越大,就越能體現出差別
3. 根據運行時間作圖
使用《算法》的API來進行作圖
public static void Draw(){
//set the size of canvas and set the Xscale and Yscale
StdDraw.setCanvasSize(800,800);
StdDraw.setXscale(0,13);
StdDraw.setYscale(0,20);
//draw the line as the Xscale and Yscale
StdDraw.line(1,3,12.5,3); //Xscale
StdDraw.line(1,3,1,18.5); //Yscale
//set the radius of the points
StdDraw.setPenRadius(0.01);
//tell the difference about two kinds of points of the two Sort method
StdDraw.text(2,19.5,"MergeSort");
StdDraw.text(2,19,"SelectSort");
StdDraw.setPenColor(Color.RED);
StdDraw.point(3,19.5);
StdDraw.setPenColor(Color.BLUE);
StdDraw.point(3,19);
//set the x_coordinate
for (int i = 2, n = 200; i <= 12 ; n += n, i += 1) {
StdDraw.text(1,2,String.valueOf(0));
StdDraw.text(i,2,String.valueOf(n),45);
}
//set the y_coordinate
for (int i = 4, n = 1; i < 19; n += 1,i++) {
StdDraw.text(0.5,3,String.valueOf(0));
StdDraw.text(0.5,i,String.valueOf(n/1.0));
}
//draw the points of the running time of MergeSort
for (int N = 200, j = 1; N <= 204800; N += N, j++){
StdDraw.setPenColor(Color.RED);
Double time1 = timeTrial1(N);
StdDraw.point(j+1, time1 + 3);
}
//draw the points of the running time of SelectSort
for (int N = 200, j = 1; N <= 204800; N += N, j++){
StdDraw.setPenColor(Color.BLUE);
Double time2 = timeTrial2(N);
StdDraw.point(j+1, time2 + 3);
}
}
會計算排序運行時間,并根據結果作圖:
由此,排序的比較就暫且告一段落了,謝謝!