标签:
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 quicksort, heapsort, 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 }
标签:
原文地址:http://www.cnblogs.com/EdwardLiu/p/4279854.html