冒泡排序、插入排序

冒泡排序:

package com.sort;
/**
 * 冒泡排序类
 * @author Maggie
 *
 */
public class BubbleSort 
{
	public void sort(int[] array)
	{
		// 需要length-1次
		for(int i = 0; i < array.length-1; i++)
		{
			// 每一伦比较之后会将最大的数放在最后面
			for(int j = 0; j < array.length-i-1; j++)
			{
				if(array[j] > array[j+1])
				{
					// 中间量
					array[j] = array[j] ^ array[j+1];
					// 交换:此时的array[j+1]其实是原来的array[j]
					array[j+1] = array[j] ^ array[j+1];
					// 交换:此时的array[j]其实是原来的array[j+1]
					array[j] = array[j] ^ array[j+1];
				}
			}
		}
	}
}


插入排序:

package com.sort;
/**
 * 插入排序
 * 思路:将待排序列的第一个插入到已排序列的合适位置
 * @author Naggie
 *
 */
public class InsertSort 
{
	public void sort(int[] array)
	{
		// 初始认为第一个数子是有序的,从第二个开始
		for(int i = 1; i < array.length; i++)
		{
			// 待排的第一个数
			int first = array[i];
			// 待比较的索引 是i的前一个
			int index = i-1;
			while(0 <= index && first < array[index])
			{
				array[index+1] = array[index];
				index--;
			}
			array[index+1] = first;
		}
	}
}


测试类:

package com.sort;

import java.util.Calendar;

/**
 * 测试类
 * @author Maggie
 *
 */
public class Test
{
	public static void main(String[] args)
	{
		// 构造一个随机待排序数组
		int[] array = new int[130000];
		for(int i = 0; i < array.length; i++)
		{
			array[i] = (int)(Math.random()*1000);
		}
//		int[] array = {99,152,2,3,88,-5,6,56,36};
		
		// 测试排序花费时间
		// 开始排序前的时间
		Calendar calendar = Calendar.getInstance();
		System.out.println("排序前的时间是:" + calendar.getTime());
		
		// 快排
//		QuickSort quick = new QuickSort();
//		quick.sort(array, 0, array.length-1);
		
		// 冒泡
//		BubbleSort bubbleSort = new BubbleSort();
//		bubbleSort.sort(array);
		
		// 插入
		InsertSort insertSort = new InsertSort();
		insertSort.sort(array);
		
		// 选择排序
//		SelectSort selectSort = new SelectSort();
//		selectSort.sort(array);
		
		// 因为calender类是单例的,只能getInstance,而且这里需要重新获取一下单例才能更新时间。
		calendar = Calendar.getInstance();
		System.out.println("排序后的时间是:" + calendar.getTime());
		
		// 输出有序序列
//		Test.showList(array);
	}
	
	public static void showList(int[] array)
	{
		for(int i= 0; i < array.length; i++)
		{
			System.out.print(array[i] + ", ");
		}
	}
	
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值