1 选择排序比冒泡排序效率高。
-
package com.lhk.sortDemo;
-
-
public interface Sort {
-
public boolean sort(int[] arr);
-
}
-
package com.lhk.sortDemo;
-
-
public class SelectSort implements Sort {
-
-
public boolean sort(int[] arr) {
-
-
if(arr == null){
-
return false;
-
}
-
-
if(arr.length <= 1){
-
return true;
-
}
-
-
-
int length = arr.length;
-
-
// 比较次数
-
int compareNum = 0;
-
-
// 交换次数
-
int swapNum = 0;
-
-
-
int min = 0;
-
for(int i = 0; i < length - 1; i++){
-
min = i;
-
for(int j = i + 1 ; j < length; j++){
-
compareNum++;
-
if(arr[min] > arr[j]){
-
min = j;
-
}
-
}
-
-
if(min != i){
-
swapNum++;
-
swap(arr, min, i);
-
}
-
}
-
-
System.out.println("对比次数: " + compareNum + " 交换次数 :" + swapNum);
-
return false;
-
}
-
-
-
private void swap(int[] arr, int start, int end){
-
// 安全性判断就不做了。。
-
int temp = arr[start];
-
arr[start] = arr[end];
-
arr[end] = temp;
-
}
-
}
-
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));
-
}
-
-
}
结果:
select sort
before sort :[1, 4, 6, 8, 1, 11, 34, 2, 67, 5, 1, 9, 10, 13, 2, 4, 5]
对比次数: 136 交换次数 :10
after sort :[1, 1, 1, 2, 2, 4, 4, 5, 5, 6, 8, 9, 10, 11, 13, 34, 67]
阅读(654) | 评论(0) | 转发(0) |