码迷,mamicode.com
首页 > 其他好文 > 详细

Summary: sorting Algorithms

时间:2015-02-08 12:50:38      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksortheapsort, or merge sort.

Time Complexity: O(N^2)

for i ← 1 to length(A) - 1
    j ← i
    while j > 0 and A[j-1] > A[j]
        swap A[j] and A[j-1]
        j ← j - 1

 

Bubble sort has worst-case and average complexity both О(n2)

First Pass:
5 1 4 2 8 ) 技术分享 ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) 技术分享 ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) 技术分享 ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) 技术分享 ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
1 4 2 5 8 ) 技术分享 ( 1 4 2 5 8 )
( 1 4 2 5 8 ) 技术分享 ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) 技术分享 ( 1 2 4 5 8 )
( 1 2 4 5 8 ) 技术分享 ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
1 2 4 5 8 ) 技术分享 ( 1 2 4 5 8 )
( 1 2 4 5 8 ) 技术分享 ( 1 2 4 5 8 )
( 1 2 4 5 8 ) 技术分享 ( 1 2 4 5 8 )
( 1 2 4 5 8 ) 技术分享 ( 1 2 4 5 8 )

 1 procedure bubbleSort( A : list of sortable items )
 2    n = length(A)
 3    repeat 
 4      swapped = false
 5      for i = 1 to n-1 inclusive do
 6        /* if this pair is out of order */
 7        if A[i-1] > A[i] then
 8          /* swap them and remember something changed */
 9          swap( A[i-1], A[i] )
10          swapped = true
11        end if
12      end for
13    until not swapped
14 end procedure

 

 selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists

Time Complexty: O(N^2)

 1 for (j = 0; j < n; j++) {
 2     iMin = j;
 3     for ( i = j+1; i < n; i++) {
 4         if (a[i] < a[iMin]) {
 5             iMin = i;
 6         }
 7     }
 8     if(iMin != j) {
 9         swap(a[j], a[iMin]);
10     }
11 }

 

Summary: sorting Algorithms

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/4279854.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!