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
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
- Merge left and right subarrays into sorted array
Merge function
- Initialise new array
- Compare first elements of left & right subarray.
- Pop the smaller/greater first element into array from (1); repeat from Step 2
- Concatenate remaining elements to the end of array from (1)
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
What is the time complexity for an Insertion Sort?
O(n²)
What is the time complexity for a Quick Sort?
O(n log n)
Under what circumstances is the quicksort least efficient?
When the provided list is nearly sorted or already sorted (pivot is not median value).
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 array.
What is the time complexity for a Bubble Sort?
O(n²)
What is the time complexity for a Merge Sort?
O(n log n)