[011]各类排序的Java实现

排序是开发中经常会用到的基本算法,学习数据结构、算法的这是入门基本功。下面就列出最常用的几类排序算法。

1、冒泡排序

冒泡排序是最大值或最小值就想气泡一样一点点生到最高层。

public class BobbleSort
{
	public static void bobbleSort(int[] a)
	{
		for(int i = 0;i < a.length;i++)
		{
			for(int j = 0;j < a.length - i - 1;j++)
			{
				if(a[j] < a[j + 1])
				{
					int temp = a[j+1];
					a[j+1] = a[j];
					a[j] = temp;
				}
			}
		}
		for(int i = 0;i < a.length;i++)
		{
			System.out.println(a[i]);
		}
	}
	public static void main(String[] args)
	{
		int[] array = {5,6,8,9,10,12,85,40,1,0};
		bobbleSort(array);
	}
}

2、快速排序

快速排序就是对半分,保证右边的所有值均大于左边的所有值,再采用递归的方式,对所有值进行排序。

public class QuickSort
{
	public static void main(String[] args)
	{
		int[] array = { 7, 1, 2, 5, 8, 9, 4, 6, 0, 3 };
		quickSort(array);
	}

	public static int sort(int[] a, int low, int high)
	{
		int l = low;
		int h = high;
		int key = a[low];
		while (l < h)
		{

			while (a[h] > key && h > low)
			{
				h--;
			}
			if (l < h)
			{
				int temp = a[l];
				a[l] = a[h];
				a[h] = temp;
			}
			while (a[l] < key && l < high)
			{
				l++;
			}
			if (l < h)
			{
				int temp = a[l];
				a[l] = a[h];
				a[h] = temp;
			}
		}
		return h;

	}

	private static void quickSort(int[] array, int low, int high)
	{
		if (low >= high || array == null)
			return;
		int l = sort(array, low, high);
		quickSort(array, low, l - 1);
		quickSort(array, l + 1, high);
	}

	public static void quickSort(int[] array)
	{
		if (array != null)
		{
			quickSort(array, 0, array.length - 1);
		}
		for (int i = 0; i < array.length; i++)
		{
			System.out.println(array[i]);
		}
	}
}

排序算法还在不断更新中。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值