Java | 数组排序算法

一、冒泡排序

冒泡排序的基本思想是对比相邻的元素值,如果满足条件就交换元素值,把较小的元素移到数组前面,把较大的元素移到数组后面(也就是交换两个元素的位置),这样较小的元素就像气泡一样从底部升到顶部。

package haha;
public class helloworld{
	public static void main(String[] args) {
		int[] array= {63,4,24,1,3,15};  //创建一个数组,元素是乱序的
		helloworld sorter=new helloworld();  //创建冒泡排序类的对象
		sorter.sort(array);
	}
	
	public void sort(int[] array) {
		for(int i=1;i<array.length;i++)
		{
			//比较相邻两个元素,较大的元素往后冒泡
			for(int j=0;j<array.length-i;j++)
			{
				if(array[j]>array[j+1])
				{
					int temp=array[j];  //把第一个元素值保留到临时变量中
					array[j]=array[j+1];  //把第二个元素的值保存到第一个元素单位中
					array[j+1]=temp;   //把临时变量(第一个元素原值)保存到第二个元素单位中
				}
			}
		}
		showArray(array);
	}
	
	public void showArray(int[] array) {
		for(int i:array)
		{
			System.out.print(">"+i);
		}
		System.out.println();
	}
}

二、直接选择排序

直接选择排序的基本思想是将指定排序位置与其他数组元素分别对比,如果满足条件就交换元素值。注意这里与冒泡排序的区别,不是交换相邻元素,而是把满足条件的元素与指定的排序位置元素交换(如从最后一个元素开始排序),这样排序好的位置逐渐扩大,直至整个数组都变成已排序好的格式。

package haha;
public class helloworld{
	public static void main(String[] args) {
		int[] array= {63,4,24,1,3,15};  //创建一个数组,元素是乱序的
		helloworld sorter=new helloworld();  //创建直接排序类的对象
		sorter.sort(array);  //调用排序类对象方法,对数组排序
	}
	
	public void sort(int[] array) {
		int index;
		for(int i=1;i<array.length;i++)
		{
			index=0;
			for(int j=1;j<=array.length-i;j++)
			{
				if(array[j]>array[index])
				{
					index=j;
				}
			}
			//交换在位置array,length-i和index(最大值)上的两个数
			int temp=array[array.length-i];
			array[array.length-i]=array[index];
			array[index]=temp;
		}
		showArray(array);
	}
	
	public void showArray(int[] array) {
		for(int i:array)
		{
			System.out.print(">"+i);
		}
		System.out.println();
	}
}

三、反转排序

反转排序的基本思想比较简单,也很好理解,其实思路就是把数组最后一个元素与第一个元素替换,倒数第二个元素与第二个元素替换,依此类推,直到把所有数组元素反转替换。

package haha;
public class helloworld{
	public static void main(String[] args) {
		int[] array= {10,20,30,40,50,60};  //创建一个数组
		helloworld sorter=new helloworld();  //创建反转排序类的对象
		sorter.sort(array);  //调用排序类对象方法,将数组反转
	}
	
	public void sort(int[] array) {
		System.out.println("数组原有内容:");
		showArray(array);
		int temp;
		int len=array.length;
		for(int i=0;i<len/2;i++)
		{
			temp=array[i];
			array[i]=array[len-i-1];
			array[len-i-1]=temp;
		}
		System.out.println("数组反转后内容:");
		showArray(array);
	}
	
	public void showArray(int[] array) {
		for(int i:array)
		{
			System.out.print("\t"+i);
		}
		System.out.println();
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天下弈星~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值