2.3.1 Algorithms Flashcards
1
Q
What is the time complexity of a binary search?
A
O (log n)
2
Q
What is the time complexity of a linear search?
A
O (n)
3
Q
What are the steps for a binary search?
A
- Start at the middle item in the list
- If the middle item is the one to be found, the search is complete.
- If the item to be found is lower than the middle item, discard all items to the right.
- If the item to be found is higher than the middle item, discard all items to the left.
- Repeat from step 2 until you have found the item or there are no more items in the list.
- If the item has been found, output item data. If it has not, output “not found.”
4
Q
What are the steps for an insertion sort?
A
- Start at the second item in the list.
- Compare current item with the first item in the sorted list.
- If the current item is greater than the item in the list, move to the next item in the sorted list.
- Repeat from step 3 until the position of the current item is less than or equal to the item in the sorted list.
- Move all the items in the list from the current position up one place to create a space for the current item.
- Insert the current item.
- Repeat from step 2 with the next item in the list until all the items have been inserted.
5
Q
What is the time complexity for the insertion sort?
A
O (n^2)
6
Q
What are the steps for a merge sort?
A
- Repeatedly divide the list in half into two smaller lists until each item is in its own list.
- Take two adjacent lists and start with the first item in each one.
- Compare the two items.
- Insert the lowest item into a new list. Move to the next item in the list it was taken from.
- Repeat step 4 until all the items from one of the lists have been put into the new list.
- Append all the items from the list still containing items to the new list.
- Remove both old lists.
- Repeat from step 2 until only one list remains
7
Q
What is the time complexity for a merge sort?
A
O (n logn)
8
Q
What are the steps in quicksort?
A
- Set the pivot value as the first item in the list.
- Set a pointer to the second and last items in the list.
- While the second pointer is greater than or equal to the first pointer:
a. Whilst the first pointer is less than or equal to the second pointer and the item at the first pointer is less than or equal to the pivot value, increase the first pointer by one.
b. Whilst the second pointer is greater than or equal to the first pointer and the item at the second pointer is greater than or equal to the pivot, decrease the second pointer by one.
c. If the second pointer is greater than the first pointer, swap the items. - Swap the pivot value with the item at the second pointer.
- Repeat from step 1 on the list of items to the left of the second pointer
9
Q
What is the time complexity of quicksort?
A
O (n logn)