Sorting Flashcards
1
Q
Selection Sort
Sort the array in ascending or descending order.
TC – O(N2)
SC – O(N)
A
Pseudo code:
- We will take two for loop.
- Outer loop will start from 0 to array length -1. (I th)
- Inner loop will start from outer loop index plus one. (J th)
- Compare outer loop indexth element to inner loop indexth element and if it’s greater than swap them.
2
Q
Bubble Sort
Sort the array in ascending or descending order.
TC – O(N2)
SC – O(N)
A
Pseudo code:
- We will take two for loop.
- Outer loop will start from 0 to array length -1. (I th)
- Initialize Boolean variable swap.
- Inner loop will start from array length -1 and j grater than outer loop indexth element. Let’s assume variable name is j. Compare adjacent element.
- Compare j and j-1th element, if it’s small than swap.
- If swapping any element then update Boolean variable to true.
- After inner loop end, check if swap variable is false, means there is no element to sort, list is sorted now, break outer loop.
Takeaway: Point 7 is making bubble sort better than selection sort.