Search and Sort Algorithm
Search and Sort Algorithm
(2)
Searching Algorithms (2) • For example:
Linear • Unsorted array
Linear/sequential search search • O(n)
• For example:
Binary search Binary • Sorted array
search • O (log n)
Metode Hash
Searching
Performance?
How to search a binary tree?
• Depends on the tree implementation
• Adjacency matrix
O(V*V)
• Adjacency list
O(V+E)
→ O(n)
Is it better than
searching on a
linked-list?
Binary Search Trees (BSTs)
Where is the
smallest element?
Ans: leftmost element
Difference between
the height of the left
subtree and right
subtree is not more
than 1.
Insert and
remove nodes
in BST Unbalanced tree
changes the
Unbalanced
tree structure tree
This is just as
good as linked
list.
This is the
worse case of
BST search →
O(n)
• Balanced Binary Search Trees
• Example: AVL tree
• It is named for its inventors: G.M. Adelson-Velskii and E.M. Landis.
• To implement our AVL tree we need to keep track of a balance factor for each node in
the tree.
Search method: Hash
• We can also store and search data by using hash table
• Store data using hash table
• Search the data from the hash table
Before hash table
there is Direct-address Tables
• Direct-address Tables are ordinary arrays.
• Facilitate direct addressing.
• Element whose key is k is obtained by indexing into the kth
position of the array.
Data
item
h(k4)
K k1 k4
(actual k2 collision h(k2)=h(k5)
keys) k5
k3
h(k3)
m–1
in a linked list. k5 k2 k6
• Open Addressing:
m–1
k1
k4
K
(actual k2 k6
keys) k5 k5 k2 k6
k8 k7
k3
k7 k3
k8
m–1
• Chained-Hash-Search (T, k)
• Search an element with key k in list T[H(k)].
• Worst-case complexity – proportional to length of list.
• Worst-case complexity: O(n) + time to compute H(k).
Searching in hash table
Sorting Algorithms (2)
Metode Shell
Bubble sort
Metode Merge
Metode Quick
Selection sort
Metode Heap
Sort method: Shell
• It first sorts elements that are far apart from each other and
successively reduces the interval between the elements to
be sorted.
Sort method:
Merge
Sort method:
Binary search
tree
Sort method:
Radix
Sort method:
Quick
Sort method: Heap
• Heap is a special tree-based data
structure.
• A binary tree is said to follow a
heap data structure if
• it is a complete binary tree
• all nodes in the tree follow the
property that they are
• greater than their children i.e. the
largest element is at the root and
• both its children and smaller than
the root and so on.
“Heapify” a tree
• Starting from a complete binary
tree, we can modify it to
become a Max-Heap by running
a function called heapify on all
the non-leaf elements of the
heap.