Basic data structures and algorithms in python
Searching algorithms in python
Linear search
|
|
Time Complexity
- Best Case: O(1) — This happens if the target element is found at the first index.
- Worst Case: O(n) — This happens if the target element is at the end of the list or not in the list at all.
- Average Case: O(n) — On average, the search will have to look through half of the list.
Space Complexity
- O(1) — The algorithm only uses a fixed amount of space regardless of the input size. There is no extra memory used other than a few variables (like i).
Binary search
|
|
Time Complexity
- Best Case: O(1) — The target is found at the middle index immediately.
- Worst Case: O(log n) — The search space is halved with each iteration.
- Average Case: O(log n) — As the search space keeps getting halved, the average time complexity is logarithmic.
Space Complexity
- O(1) — Only a few variables are used (like left, right, mid), so the space complexity is constant.
Sorting algorithms
Bubble sort
|
|
Time Complexity:
- Best Case: O(n) — This happens if the array is already sorted, and the algorithm will only go through one pass.
- Worst Case: O(n²) — The algorithm must compare each element with every other element.
- Average Case: O(n²) — On average, the algorithm will make about n²/2 comparisons.
Space Complexity:
- O(1) — Only a constant amount of space is used for swapping elements.
Insertion sort
|
|
Time Complexity:
- Best Case: O(n) — This happens when the array is already sorted, and no shifts are needed.
- Worst Case: O(n²) — This happens when the array is sorted in reverse order, and every element must be compared and shifted.
- Average Case: O(n²) — Similar to the worst case, but on average, half of the comparisons will be needed for each element.
Space Complexity:
- O(1) — Only a constant amount of space is used for the key variable and a few comparisons.
Quick sort
|
|
Time Complexity:
- Best Case: O(n log n) — This happens when the pivot divides the array into roughly equal parts each time.
- Worst Case: O(n²) — This happens when the pivot is the smallest or largest element, causing the array to be split in a very unbalanced way.
- Average Case: O(n log n) — On average, the pivot divides the array fairly evenly.
Space Complexity:
- O(log n) — Due to the recursion stack, as the depth of recursion is proportional to log n for balanced partitions.