-
package com.lhk.sortDemo;
-
-
public interface Sort {
-
public boolean sort(int[] arr);
-
}
-
package com.lhk.sortDemo;
-
-
public class InsertSort implements Sort {
-
-
public boolean sort(int[] arr) {
-
if(arr == null){
-
return false;
-
}
-
-
if(arr.length <= 1){
-
return true;
-
}
-
-
// 比较次数
-
int compareNum = 0;
-
-
// 交换次数
-
int swapNum = 0;
-
-
int length = arr.length;
-
-
int temp;
-
int j;
-
for(int i = 1; i < length ; i++){
-
compareNum++;
-
if(arr[i] < arr[i - 1]){
-
temp = arr[i];
-
for(j = i - 1; arr[j] > temp; j--){
-
arr[j+1] = arr[j];
-
swapNum++;
-
}
-
arr[j + 1] = temp;
-
swapNum++;
-
}
-
}
-
-
System.out.println("对比次数: " + compareNum + " 交换次数 :" + swapNum);
-
return true;
-
}
-
}
-
package com.lhk.sortDemo;
-
-
import java.util.Arrays;
-
-
public class SortDemo1 {
-
-
/**
-
* @param args
-
*/
-
public static void main(String[] args) {
-
-
int[] arr = {1,4,6,8,1,11,34,2,67,5,1,9,10,13,2,4,5};
-
-
// 冒泡排序
-
// Sort bubbleSort = new BubbleSort();
-
// System.out.println("bubble sort");
-
// System.out.println("before sort :" + Arrays.toString(arr));
-
// bubbleSort.sort(arr);
-
// System.out.println("after sort :" + Arrays.toString(arr));
-
-
// 选择排序
-
// Sort selectSort = new SelectSort();
-
// System.out.println("select sort");
-
// System.out.println("before sort :" + Arrays.toString(arr));
-
// selectSort.sort(arr);
-
// System.out.println("after sort :" + Arrays.toString(arr));
-
-
// 直接插入排序
-
Sort insertSort = new InsertSort();
-
System.out.println("insertSort sort");
-
System.out.println("before sort :" + Arrays.toString(arr));
-
insertSort.sort(arr);
-
System.out.println("after sort :" + Arrays.toString(arr));
-
}
-
-
}
运行结果:
insertSort sort
before sort :[1, 4, 6, 8, 1, 11, 34, 2, 67, 5, 1, 9, 10, 13, 2, 4, 5]
对比次数: 16 交换次数 :66
after sort :[1, 1, 1, 2, 2, 4, 4, 5, 5, 6, 8, 9, 10, 11, 13, 34, 67]
阅读(714) | 评论(0) | 转发(0) |