2.1.3 Searching and Sorting Algorithms Flashcards
Standard Algorithm
Pre loaded to perform a basic task
Sorting and Searching algorithm
Examples of Sorting algorithms
Sorting - Bubble sort, Merge sort, Insertion sort
What is Bubble sort?
Each item in a list is compared to the next item. If a swap is needed they will swap. Continue to end of list for a pass
Example of Bubble Sort
Data = 5,3,4,7,6,9
Data = (5,3,4,7,6,9)
3,5,4,7,6,9
3,4,5,7,6,9
3,4,5,6,7,9
Pass 1
Example of Bubble sort with 2 passes
Data = Dan,Ben,Bob,Tom,Sam,Liz
Data = (Dan,Ben,Bob,Tom,Sam,Liz)
Ben, Dan, Bob, Tom, Sam, Liz
Ben, Bob, Dan, Tom, Sam, Liz
Ben, Bob, Dan, Sam, Tom, Liz
Ben, Bob, Dan, Sam, Liz, Tom
Pass 1
Ben, Bob, Dan, Liz, Sam, Tom
Pass 2
What is a merge sort?
The data is broken down, broken down again until single values. Values will be merged into pairs while sorting
Example of Merge sort
Data = 10,1,13,24,7,5,36,25
Data = 10,1,13,24,7,5,36,25
10,1,13,24 7,5,36,25
10,1 13,24 7,5 36,25
10 1 13 24 7 5 36 25
1,10 13,24 5,7 25,36
1,10,13,24 5,7,25,36
1,5,7,10,13,24,25,36
What is an Insertion algorithm?
Value will be removed from an unsorted list and placed in the correct location in a sorted list
Example of Insertion sort
Data = 15,12,13,10,9,14
Data = (15,12,13,10,9,14)
Sorted: (15) 12,13,10,9,14
(12,15) 13,10,9,14
(12,13,15) 10,9,14
(10,12,13,15) 9,14
(9,10,12,13,15) 14
(9,10,12,13,14,15)
Examples of Searching algorithms
Searching - Linear search and Binary search
What is a Linear Search?
Starting from the beginning of the list, compare a search value to the first item in the list, continue comparing in order until item is found or not found
Example of Linear search
Data = Ben,Bob,Tom,Sam,Dan,Ali
Data = (Ben,Bob,Tom,Sam,Dan,Ali)
Search Value = Tom
Compare Tom to Ben (Index 0) No Match
Compare Tom to Bob (Index 1) No Match
Compare Tom to Tom (Index 2) Found
Example of Linear search
Data = 5,3,4
Data = (5,3,4)
Search Value = 10
Compare 10 to 5 (Index 0) No Match
Compare 10 to 3 (Index 1) No Match
Compare 10 to 4 (Index 2) No Match
Item not found
What is Binary Search?
- Data has to be sorted
- Set a middle boundary
- Compare search value to middle boundary
- If it’s a match - found
- If less than, Discard the upper side and left
- If more than, Discard the lower side and right
- Repeat the process
Number of values div 2 = Index of MB
Example of Binary search
Data = 1,2,3,4,5,6,7,8,9
Data = (1,2,3,4,5(MB),6,7,8,9)
Search Value = 8
Compare 8 to 5 (MB) Not a Match
8>5 so discard the lower side
go to the upper side
Compare 8 to 8(MB) Match item found