Sort algorithms Flashcards
The key steps for Bubble Sort are:
- Iterate through each pair of elements (i, i+1)
- Compare them; swap them if not in the desired order
(largest/smallest element should be at end of array after first iteration) - Repeat for subsequent iterations, excluding the most recently sorted value
The key steps for Insertion Sort are:
- Assume the first element is sorted.
- Iterate through each subsequent element (in the unsorted subarray): this is the target.
- Determine the most appropriate place in sorted subarray to insert the target element
- Carry out the insertion using pop/insert
The key steps for Merge Sort are:
- Handle the base case (empty/single-element array)
- Split the array into left and right subarrays
- Recursively sort the left and right subarrays
- Pass left and right subarrays to merge function to obtain sorted array
Merge function
- Initialise empty array (
arr
) - Check if left or right subarrays are empty; if either is empty, return arr + left + right
- If both are not empty, compare first elements of left & right subarray.
- Pop the smaller/greater first element into
arr
; repeat from Step 2
The key steps for Quick Sort are:
- Handle the base case (empty/single-element array)
- Select pivot (can use last element)
- Initialise less-than (
lt
) and greater-than-equal (gte
) subarrays - Iterate through all elements except pivot; if element less than pivot, append to
lt
; if element greater than or equal pivot, append togte
. - Recursively sort
lt
andgte
- Recombine
lt
,gte
, and pivot into a single array
Which two sorts are in-place?
- Bubble Sort
- Insertion Sort
[Merge Sort and Quick Sort are both out-of-place]
What is the time complexity for an Insertion Sort?
O(n^2)
Under what circumstances is the quicksort most suboptimal?
When the provided list is nearly sorted or already sorted.
What is the time complexity for a Quick Sort?
O(n log n)
What does it mean when a sorting algorithm is said to be ‘stable’?
A stable sorting algorithm ensures that elements with identical sorting properties still maintain their original order.
What is the key determining factor that affects the execution time of a sort algorithm?
The size of the given list.