Strategy Pattern Sorter - Problem
Implement a flexible sorting system using the Strategy Pattern that can dynamically switch between different sorting algorithms at runtime.
Your task is to create a Sorter class that can use three different sorting strategies:
- Bubble Sort: Repeatedly compares adjacent elements and swaps them if they're in wrong order
- Insertion Sort: Builds the sorted array one element at a time by inserting each element in its correct position
- Selection Sort: Finds the minimum element and places it at the beginning, then repeats for remaining elements
The system should accept an array of integers and a strategy name ("bubble", "insertion", or "selection"), then return the sorted array using the specified algorithm.
This demonstrates the Strategy Pattern's power to swap algorithms without changing the client code, making your sorting system extensible and maintainable.
Input & Output
Example 1 — Bubble Sort Strategy
$
Input:
arr = [64,34,25,12], strategy = "bubble"
›
Output:
[12,25,34,64]
💡 Note:
Using bubble sort: repeatedly compares adjacent elements [64,34] → [34,64], then [64,25] → [25,64], etc. After multiple passes, smallest elements "bubble up" to correct positions.
Example 2 — Insertion Sort Strategy
$
Input:
arr = [5,2,4,6,1,3], strategy = "insertion"
›
Output:
[1,2,3,4,5,6]
💡 Note:
Using insertion sort: takes each element and inserts it into correct position in the already-sorted left portion. Like organizing playing cards in your hand.
Example 3 — Selection Sort Strategy
$
Input:
arr = [29,10,14,37,13], strategy = "selection"
›
Output:
[10,13,14,29,37]
💡 Note:
Using selection sort: finds minimum element (10) and places it first, then finds next minimum (13) and places it second, repeating until sorted.
Constraints
- 1 ≤ arr.length ≤ 1000
- -1000 ≤ arr[i] ≤ 1000
- strategy ∈ {"bubble", "insertion", "selection"}
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code