冒泡排序,选择排序,插入排序的比较

本文对比了冒泡排序、选择排序和插入排序三种经典排序算法在处理不同大小数组时的性能表现,通过实验证明选择排序在给定场景下具有最佳效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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毫秒
 */
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值