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就是最小的。但是當然,爲了嚴謹與保證完全正確,還是要注意 的




發佈了112 篇原創文章 · 獲贊 15 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章