Introduction to Sorting Algorithms
Introduction to Sorting Algorithms
• Pass 1:
• Compare 4 and 2 → Swap: [2, 4, 3]
• Compare 4 and 3 → Swap: [2, 3, 4]
• End of Pass 1: [2, 3, 4]
• Disadvantages:
– Very slow for large datasets (O(n²) time complexity).
– Inefficient compared to more advanced algorithms.
What is Selection Sort?
• Definition: Another comparison-based sorting algorithm.
• Working: It repeatedly selects the smallest element from the
unsorted portion and swaps it with the first unsorted element.
• Not stable: It may change the relative order of equal elements.
• In-place: No additional memory needed.
Selection Sort Example
• Initial Array: [3, 1, 2]
• Pass 1:
• Find the minimum: 1 (index 1)
• Swap with first element (3):
• Array: [1, 3, 2]
• Pass 2:
• Find the minimum in the remaining array: 2 (index 2)
• Swap with second element (3):
• Array: [1, 2, 3]
• Final Sorted Array:
•The array is now sorted: [1, 2, 3].
Selection Sort: Pseudocode
for each element in the list
find the minimum element in the unsorted part
swap it with the first unsorted element
• Disadvantages:
– Inefficient for large datasets (O(n²) time complexity).
– Slower than more advanced algorithms like Quick Sort or Merge
Sort.
Conclusion
• Bubble Sort and Selection Sort are simple but inefficient for large
datasets.
• Both have a time complexity of O(n²).
• Bubble Sort swaps adjacent elements, while Selection Sort selects
the smallest element and swaps.
• Useful for learning basic sorting, but advanced algorithms are
better for real-world use.