上次我们说到二叉树排序比较,给出如下的题目
题目:创建五万个随机数,然后用分别用冒泡法,选择法,二叉树3种排序算法进行排序,比较哪种更快
废话不说直接上源码,可以看控制台结果
注意的是
需要我们需要上一篇中的Node.java 有需要的同学可以参考java中级——集合框架【2】-二叉树
package cn.jse.node;
import java.util.Arrays;
import java.util.List;
public class SortCompare {
public static void main(String[] args) {
//初始化随机数(new 一个长度为total的nums数组)
int total=50000;
int[] nums = new int[total];
for(int i=0;i<nums.length;i++){
nums[i] = (int)(Math.random()*total);
}
System.out.println("已经初始化50000随机数的数组,我们将会使用3中方法进行排序");
int[] mysort;
mysort=Arrays.copyOf(nums, nums.length);
int[] sortBySelection = performance(new SelectionSort(mysort),"选择排序法");
mysort=Arrays.copyOf(nums, nums.length);
int[] sortByBubbling = performance(new BubblingSort(mysort),"冒泡排序法");
mysort=Arrays.copyOf(nums, nums.length);
int[] sortByTree = performance(new TreeSort(mysort),"二叉树排序法");
}
interface Sort{
void sort();
int[] values();
}
//选择法
static class SelectionSort implements Sort{
int numbers[];
SelectionSort(int[] numbers){
this.numbers = numbers;
}
@Override
public void sort() {
// TODO Auto-generated method stub
for(int j=0; j<numbers.length-1;j++){
for(int i=0;i<numbers.length;i++){
if(numbers[i]<numbers[j]){
int temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
}
}
}
@Override
public int[] values() {
// TODO Auto-generated method stub
return null;
}
}
//冒泡排序
static class BubblingSort implements Sort{
int numbers[];
BubblingSort(int [] numbers){
this.numbers = numbers;
}
@Override
public void sort() {
for (int j = 0; j < numbers.length; j++) {
for (int i = 0; i < numbers.length-j-1; i++) {
if(numbers[i]>numbers[i+1]){
int temp = numbers[i];
numbers[i] = numbers[i+1];
numbers[i+1] = temp;
}
}
}
}
@Override
public int[] values() {
// TODO Auto-generated method stub
return numbers;
}
}
//二叉树排序
static class TreeSort implements Sort{
int numbers[];
Node n;
TreeSort(int [] numbers){
n =new Node();
this.numbers = numbers;
}
@Override
public void sort() {
for (int i : numbers) {
n.addData(i);
}
}
@Override
public int[] values() {
return null;
}
}
private static int[] performance(Sort algorithm, String type) {
long start = System.currentTimeMillis();
algorithm.sort();
int sortedNumbers[] = algorithm.values();
long end = System.currentTimeMillis();
System.out.printf("%s排序,一共耗时 %d 毫秒%n",type,end-start);
return sortedNumbers;
}
}