Sorting Flashcards
How does Quick Sort work?
- Randomly select a pivot
- Using the left index and right index, increment the left index and decrement the right index until the left index finds a value that is greater than pivot, and the right index finds a value that is less than pivot. Swap those values. Continue until left index == right index.
- Swap the pivot with the left index when it is over.
- Recursively execute the quick sort on the left partition and right partition of the array.
What is the best and worst case time complexity of Quick Sort?
Best: O(nlogn)
Worst: O(n^2)
What is the best and worst case space complexity of Quick Sort?
Best: logn
Worst: n
How does Merge Sort work?
Divide and Conquer (Recursive algorithm)
1. Split the array into the left and right halves and keep on splitting until they reach their individual elements
2. Merge the individual elements into a sorted sublist -> 1 & 3 -> 1,3.
3. With each sorted sublist, compare the first element of each sublist and add the smaller element to a combined list. After adding, increment the index until one of the sublist runs out and add the remaining elements of the other list.
What is the best and worst case time complexity of Merge Sort?
O(nlogn)
What is the best and worst case space complexity of Quick Sort?
log n
How does Insertion Sort work?
- For each element from the second element of the list to the end, traverse each element to the left side of it and if that element is greater than the reference element, shift the element to the right. Once it finds an element smaller than it, stop and insert it there.
What is the best and worst case time complexity of Insertion Sort?
Best: O(n)
Worst: O(n^2)
What is the best and worst case space complexity of Insertion Sort?
Best and Worst: O(1)
How does Bubble Sort work?
- For each element from the first to the second last, compare it to the element ahead of it. If it is greater, swap. Through the first iteration, the greatest number will be at the end of the list, and through the second iteration, the second greatest number will be the second last element of the list.
What is the best and worst case time complexity of Bubble Sort?
Best: O(n)
Worst: O(n^2)
What is the best and worst case space complexity of Bubble Sort?
Best and Worst: O(1)
How doe Selection Sort work?
- For each element from the first to the second last, compare it with every element to the right of it and find the minimum. Swap the minimum with the element.
What is the best and worst case time complexity of Selection Sort?
best case and worst case: O(n^2)
What is the best and worst case space complexity of Bubble Sort?
best & worst cases: O(1)