java 13:数组排序——选择排序及插入排序

1 选择排序

Suppose that you want to sort a list in ascending order. Selection sort finds the smallest num-
ber in the list and places it first. It then finds the smallest number remaining and places it next
to first, and so on, until only a single number remains. 

假如是要求升序,选择排序的关键就是每次在数组中选择一个最小的元素,然后插到第一个位置,继续找剩下元素中的最小放到第二个位置这样,一直找到剩下最后一个元素就完成了排序

public class SelectionSort
{
	public static void selectionSort(int [] a)
	{
		int min;
		int index;
		for(int i=0;i<a.length;i++)
		{
			min=a[i];
			index=i;
			for(int j=i+1;j<a.length;j++)
			{
				if(a[j]<min) 
				{
					min=a[j];
					index=j;
				}
			}
			a[index]=a[i];
			a[i]=min;
			
		}
	}
	public static void main(String [] args)
	{
		int [] a={2,4,72,34,0,67,3};
		selectionSort(a);
		for(int i=0;i<a.length;i++)
		{
			System.out.print(a[i]+"    ");
		}
	}
}

2 插入排序

Suppose that you want to sort a list in ascending order. The insertion-sort algorithm sorts a list
of values by repeatedly inserting a new element into a sorted sublist until the whole list is sorted

for (int i = 1; i < list.length; i++) {
insert list[i] into a sorted sublist list[0..i-1] so that
list[0..i] is sorted.
}

To insert list[i] into list[0..i-1], save  list[i] into a temporary variable, say
currentElement. Move  list[i-1] to list[i] if list[i-1] > currentElement,
move  list[i-2] to list[i-1] if list[i-2] > currentElement, and so on, until
list[i-k] <= currentElement or k>i (we pass the first element of the sorted list).
Assign currentElement to list[i-k+1]. 

也就是说,我们遍历数组,然后遇到一个元素就处理该元素,将它插入到前边已经拍好的合适的位置上,为了将list[i]插入到已经排好序的list[0...i-1]中,我们可以用一个cur变量来暂时存放list[i] 。如果cur<list[i-1] 则将list[i-1] 放到list[i]位置;如果cur<list[i-2] 则将list[i-2]移到list[i-1]位置,这样下去,直到list[i-k]<=cur 或则i-k<0时候,cur插入的位置就是list[i-k+1];

public class InsertSort
{
	public static void insertSort(int [] a)
	{
		int cur,j;
		<span style="color:#ff0000;">for(int i=1;i<a.length;i++)
		{
			//if(a[i]>=a[i-1]) continue;
			cur=a[i];
			j=i-1;
			while(j>=0&&cur<a[j])
			{
					a[j+1]=a[j];
					j--;
			}
			a[j+1]=cur;
		}</span>
	}
	public static void main(String [] args)
	{
		int [] a={2,4,72,34,0,67,3};
		insertSort(a);
		for(int i=0;i<a.length;i++)
		{
			System.out.print(a[i]+"    ");
		}
	}
}
这里一定注意
<span style="color:#ff0000;">while(j>=0&&cur<a[j])</span>
必须j>=0写在前边,不然运行时候会出现 超过数组边界的错误。开始时候自己写将她放在后面,一直在运行时候就通不过。后来模拟一下才知道问题。因为当前元素是最小的必须拍到第一位,那么当我们j=0时候,依旧条件成立,这时候在循环体中j会被我们置为了-1 ,然后再进行while时候,cur<a[j],a[j]就是a[-1]了,这时候就会出错。其实如果我们将其中的0元素去掉,也就是原来数组的第一个元素就是最小的了,这样在后面的比较中都不会比较到这个index=0的位置来,这时候运行不会出错的,大家可以试着将原数组0去掉,这样2就是最小的。但是当然,为了严谨与保证完全正确,还是要注意 的




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值