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
Strategy Pattern SorterINPUT64342512arr = [64,34,25,12]strategy = "bubble"ALGORITHM STEPS1Create SortStrategy interface2Implement BubbleSort strategy3Select strategy from context map4Execute bubble sort algorithmBubble Sort Process:Pass 1: [34,25,12,64]Pass 2: [25,12,34,64]Pass 3: [12,25,34,64]Pass 4: [12,25,34,64] ✓No swaps needed - sorted!FINAL RESULT[12,25,34,64]Sorted ArrayStrategy Pattern Success:Bubble sort strategyexecuted correctlyAlgorithm swappedwithout changingclient code-->-->Key Insight:The Strategy Pattern encapsulates algorithms in separate classes, allowingdynamic algorithm selection without modifying the client code structure.TutorialsPoint - Strategy Pattern Sorter | Complete OOP Implementation
Asked in
Google 45 Amazon 38 Microsoft 42 Apple 35
23.4K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen