Basic sorting algorithms
Heap Sort (or Heap Sort)
(heap) β , , : -, , , , -, max- min-. min-.
β , . , , , , .
:
HeapSort(A[1β¦n]):
1 - H = buildHeap(A[1β¦n])
2 - for i = 1 to n do:
3 - A[i] = extract-min(H)
. β ; min-. , min-. , , , buildHeap
.
buildHeap
:
buildHeap():
1 - H
2 - for i = 1 to n do:
3 - Add(H, A[i])
min-, , . , , min- - , , . , , , .
, . , , ( extract-min). -: , ! , , , , , , heapify
( ).
extract-min heapify:
extract-min(H):
1 - min = H[1]
2 - H[1] = H[H.size()]
3 - H.size() 1
4 - heapify(H, 1)
5 - return min
heapify():
1 - n = H.size()
2 - while (LeftChild(i) <= n and H[i] > H[LeftChild(i)]) or (RightChild(i) <= n and H[i] > H[RightChild(i)]) do:
3 - if (H[LeftChild(i)] < H[RightChild(i)]) then:
4 - j = LeftChild(i)
5 - else:
6 - j = RightChild(i)
7 - H[i] H[j]
8 - i = j
! , . , , , . O(n log n).
(Merge Sort)
β , , . , . .
β Β« Β», 3 :
() «» .
() . , , β , .
, , , , !
« » , , , . , . , , «», . « », .
mergeSort
:
, .
mergeSort
, (), ( ).
:
Merge(A, B):
1 - i = 1; j = 1; k = 1;
2 - a_(m+1) = β; b_{n+1} = β
3 - while (k <= m+n) do:
4 - if (a_i < b_j) then
5 - c_k = a_i; i++;
6 - else
7 - c_k = b_j; j++;
8 - k++;
9 - return C = {c_1, c_2, β¦, c_(m+n)}
MergeSort(X, n)
1 - if (n == 1) return X
2 - middle = n/2 (round down)
3 - A = {x_1, x_2, β¦, x_middle}
4 - B = {x_(middle+1), x_{middle+2), β¦, x_n}
5 - As = MergeSort(A, middle)
6 - Bs = MergeSort(B, n - middle)
7 - return Merge(As, Bs)
, , , , . O(n log n).
( , Convex Hull)
. β , .
1 β (Gift Wrapping) O(nΒ²)
, ( x) . p , , . :
1 - ConvexHull =
2 - x u (:= u_original)
3 - L , u
3 - Do:
4 - v L u * v
5 - v ConvexHull
6 - L = uv
7 - u := v
8 - Until v = u_original
9 - ConvexHull
2 β (Graham Scan) O(n log n)
2 :
1 ( ): . , , . . ? , . , .
2 ( ): , , . . , . : prev(p), curr(c) next(n). ( ) , c, .
1 - ConvexHull =
2 - u - x ( , , y)
3 - u
4 - u ConvexHull
5 - For i = 2 to n - 1:
6 - While , i > 180 :
7 - ConvexHull
8 - i ConvexHull
9 - Return ConvexHull
β β
, Medium GitHub, https://jameskle.com/. , LinkedIn. , !
- Β« Β». - :β , β () β . . .