Dsa Basic Notes
Dsa Basic Notes
l = 2i
r = 2i + 1
largest = i
if l <= A.heap_size and A[l] > A[largest]
largest = l
if r <= A.heap_size and A[r] > A[largest]
largest = r
if largest != i
SWAP(A[i], A[largest])
MAX-HEAPIFY(A, largest)
BUILD-MAX-HEAP(A,n) // n is heap_size
A.heap_size = n
for i = floor(n/2) downto 1
MAX-HEAPIFY(A,i)
HEAPSORT(A,n) // O (n log n)
BUILD-MAX-HEAP(A,n) // O (n)
for i = n down to 2 // O (n-1)
SWAP(A[1], A[i])
A.heap_size = A.heap_size - 1
MAX-HEAPIFY(A,1) // O(log n)
MAX-HEAP-INSERT(A,x) // insert for MAX HEAP, assuming heap size can increase
infinitely
A.heap_size = A.heap_size + 1
A[A.heap_size] = x
i = heap_size
parent = floor(i/2)
while i > 1 and A[parent] < A[i]
SWAP(A[parent], A[i])
i = parent
parent = floor(i/2)
MAX-HEAP-EXTRACT-MAXIMUM(A) // O (log n)
max = A[1]
A[1] = A[A.heap_size]
A.heap_size--
MAX-HEAPIFY(A,1)
return max
TREES
//size of A is equal to total nodes in the tree
INORDER(ROOT, A, i)
if ROOT is null
return i
i = INORDER(ROOT.LEFT, A, i)
A[i] = ROOT.data
i = INORDER(ROOT.RIGHT, A, i+1)
return i
PREORDER(ROOT, A, i)
if ROOT is null
return i
A[i] = ROOT.data
i = PREORDER(ROOT.LEFT, A, i+1)
i = PREORDER(ROOT.RIGHT, A, i)
return i
POSTORDER(ROOT, A, i)
if ROOT is null
return i
i = POSTORDER(ROOT.LEFT, A, i)
i = POSTORDER(ROOT.RIGHT, A, i)
A[i] = ROOT.data
return i + 1
// BST
BSTinsert(ROOT,k)
if ROOT is null
return ROOT = new NODE with data = k
if ROOT.data = k
return ROOT
if k < ROOT.data
ROOT.LEFT = BSTinsert(ROOT.LEFT, k)
else
ROOT.RIGHT = BSTinsert(ROOT.RIGHT, k)
return ROOT
BSTsearch(ROOT, k)
if ROOT is null
return NEW ROOT with ROOT.data = -inf
if ROOT.data = k
return ROOT
if k < ROOT.data
return BSTsearch(ROOT.LEFT, k)
else
return BSTsearch(ROOT.RIGHT, k)
SORTS
N^2 SORTS
BUBBLESORT(A) // check this and next and swap if this > next, do this n times
(take the current and put it at the farthest)
n = A.length
for i = 1 to n
for j = 1 to n - i
if A[j] > A[j+1]
SWAP(A[j],A[j+1])
n = A.length
for i = 1 to n - 1
min = i
for j = i + 1 to n
if A[j] < A[min]
min = j
SWAP(A[j], A[min])
INSERTIONSORT(A) //
n = A.length
for i = 2 to n
key = A[i]
j = i-1
while j > 0 and A[j] > key
A[j+1] = A[j]
j = j-1
A[j+1] = key
N LOG N SORTS
MERGESORT(A,lo,hi)
MERGESORT(A,lo,mid)
MERGESORT(A,mid,hi)
MERGE(A,lo,mid,hi)
MERGE(A,lo,mid,hi)
i = lo
j = mid
k=0
for i = 0 to A1.length
A[lo+i] = A1[i]
QUICKSORT(A,lo,hi) //log n
p = PARTITION(A,lo,hi)
QUICKSORT(A,lo,p)
QUICKSORT(A,p+1,hi)
PARTITION(A,lo,hi)
pivot = A[floor((lo+hi)/2)]
i = lo-1
j = hi+1
while True:
do i ++ while i < hi and A[i] < pivot
if (i >= j)
return j
SWAP(A[i], A[j])
GRAPHS
BFS (G, s)
Enqueue(s)
T.add(s) // T is the traversed set
while Queue is not Empty
u = dequeue()
for each vertex v that has an edge with u
if v not in T
enqueue(v)
T.add(v)
DFS (G, s)
T.add(s)
for each vertex v that has an edge with s
if v not in T
DFS(G,v)
DJIKSTRA(G,s)
for all vertices u in G.V
u.dist = inf
u.parent = NIL
s.dist = 0
PQ.addAll(G.V)