package com.sort;
import java.util.Random;
/**
* @author 鲁志明 E-mail: 13688601037@139.com
* @version 创建时间:2013-6-5 下午8:19:46
*
*/
public class HomeWork {
// 冒泡排序 - 把最大放到右侧
public static void bubbleSort(int[] array)
{
for(int out = 0 ; out <array.length-1 ; out++)
{
for(int in = 0 ; in < array.length -out -1 ; in++)
{
if(array[in] > array[in+1])
{
int tem = array[in];
array[in] = array[in+1];
array[in+1] = tem;
}
}
}
}
// 选择排序 - 每次选择出一个最小的放到最左边
public static void selectionSort(int[] array)
{
for(int out = 0 ; out < array.length ; out ++)
{
int min = out ;
for(int in = out ; in < array.length ; in++)
{
if(array[in] < array[min])
{
min = in;
}
}
// 提升效率
if(min != out)
{
int tem = array[min];
array[min] = array[out];
array[out] = tem;
}
}
}
// 插入排序 - 由后向前扫描,
public static void insetionSort(int[] array)
{
int in;
for(int out = 1; out < array.length ; out++)
{
int tem = array[out];
in = out;
while(in > 0&&tem<array[in-1])
{
// 前一个元素向后移动一个位置,为tem(未排序元素空出位置来)
array[in] = array[in -1];
array[in -1] = tem ;
in -- ;
}
}
}
// 生成新数组
public static int[] getNewInt(int[] array)
{
Random random = new Random();
for(int i = 0 ; i < array.length ; i++)
{
array[i] = random.nextInt(1000);
}
return array;
}
public static void main(String[] args) {
Random random = new Random();
int[] array = new int[10000];
// 冒泡排序测试
array = getNewInt(array);
long before = System.currentTimeMillis();
bubbleSort(array);
long after = System.currentTimeMillis();
System.out.println("冒泡排序用的时间:"+(after - before)+"毫秒");
// 选择排序测试
array = getNewInt(array);
before = System.currentTimeMillis();
selectionSort(array);
after = System.currentTimeMillis();
System.out.println("选择排序用的时间:"+(after - before)+"毫秒");
// 插入排序测试
array = getNewInt(array);
before = System.currentTimeMillis();
insetionSort(array);
after = System.currentTimeMillis();
System.out.println("插入排序用的时间:"+(after - before)+"毫秒");
/**
冒泡排序用的时间:219毫秒
选择排序用的时间:62毫秒
插入排序用的时间:31毫秒
*/
}
}
冒泡排序,选择排序,插入排序的比较
最新推荐文章于 2021-03-11 02:10:34 发布