选择排序的基本思想是对待排序的记录序列进行n-1遍的处理,第i遍处理是将L[i..n]中最小者与L[i]交换位置。这样,经过i遍处理之后,前i个记录的位置已经是正确的了。 选择排序算法可实现如下: procedure Selection_Sort(var L:List); var i,j,s:position; begin 1 for i:=First(L) to Last(L)-1 do begin 2 s:=i; 3 for j:=i+1 to Last(L) do 4 if L[j]< L[s] then 5 s:=j; //记录L[i..n]中最小元素的位置 6 swap(L[i],L[s]); //交换L[i],L[s] end; end; 算法Selection_Sort中里面的一个for循环需要进行n-i次比较,所以整个算法需要 次比较。 显而易见,算法Selection_Sort中共调用了n-1次swap过程。选择排序法是一个原地置换排序法,也是稳定排序法。 |
This blog is meant for my personal reference and keeping track of what I have learnt. Most articles are found through search engines, if you are the author of the article and would like to remove from this blog, please contact me.
Monday, May 16, 2011
比较排序算法——选择排序(Selection Sort)
Labels:
Algorithm
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment