Algorithm|Javascript Algorithm

Selection Sort: The Persistence to Find the Minimum

0
Selection Sort: The Persistence to Find the Minimum

Chris just tried sorting 100 data items using the Bubble Sort he learned recently.

The result was shocking. If luck is not on his side, it swaps positions thousands of times to complete the sort.

"Wait, can't we just find the smallest number and move it to the front just once?"

"Why waste energy constantly swapping with the neighbor?"

Chris's intuition was correct. The method that drastically reduces the brute-force swap count of Bubble Sort is Selection Sort.

1. "I'll Pick Only You"

The idea behind Selection Sort is very human. It is similar to the method we unconsciously use when organizing cards.

  • Scan the entire deck to find the smallest number (Minimum).
  • Swap that card with the card at the very front.
  • Since the front is now sorted, leave it alone. Scan from the second slot to the end to find the minimum again.
  • Swap that card with the second slot.
  • (Repeat)
  • If Bubble Sort is "I swap if I am bigger than my neighbor,"

    Selection Sort is "I scan to the end, Select the smallest one, and bring it over."

    2. Implementing in JavaScript

    When implementing in code, you need a variable to remember "the location (index) of the minimum value found so far."

    javascript
    function selectionSort(arr) {
      for (let i = 0; i < arr.length; i++) {
        // 1. Assume the current position (i) is the smallest for now.
        let lowest = i;
    
        // 2. Scan from i+1 to the end to find the real minimum.
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[j] < arr[lowest]) {
            lowest = j; // "Found it! You are the new minimum."
          }
        }
    
        // 3. Swap only if the minimum is not the current position.
        // (No need to swap if it is already the minimum)
        if (i !== lowest) {
          console.log(`Swap: {arr[i]} <-> {arr[lowest]}`);
          [arr[i], arr[lowest]] = [arr[lowest], arr[i]];
        }
      }
      return arr;
    }
    
    selectionSort([34, 22, 10, 19, 17]);

    3. Performance Analysis: Is it Better than Bubble Sort?

    Let's calculate the Time Complexity of this code.

  • Comparisons: Same as Bubble Sort. It has to scan to the end using nested loops, so it compares roughly N^2 times. → O(N^2)
  • Swaps: This is the key. Bubble Sort swaps frequently, but Selection Sort swaps at most once per loop. → O(N)
  • In conclusion, the Time Complexity itself is O(N^2), same as Bubble Sort, so it is still slow when data increases.

    However, in a memory environment where the "Write/Swap" operation is very expensive, Selection Sort can be much more efficient than Bubble Sort.

    4. The Fatal Flaw of Selection Sort

    Selection Sort has one fatal flaw: it is an Unstable Sort.

    When there are duplicate values (e.g., [3, 3]), the 3 that was behind might jump to the front during the sorting process, flipping their original order.

  • Example: When sorting [5, 5, 1], the first 5 swaps with 1, moving behind the second 5.
  • Key Takeaways

  • Principle: Scan the whole, 'Select' the minimum, and bring it to the front.
  • Time Complexity: O(N^2). Still slow.
  • Pros: Significantly fewer Swaps compared to Bubble Sort. The logic is intuitive.
  • Cons: It unconditionally compares to the end even if the data is already sorted (hard to optimize), and it is an Unstable Sort.

  • We have learned "Sending large numbers to the back (Bubble)" and "Bringing small numbers to the front (Selection)."

    However, there is a method we actually use when playing card games. It's the method of picking up one card at a time and "inserting it into the appropriate spot."

    Let's meet Insertion Sort, which is the fastest among existing sorting algorithms when data is nearly sorted.

    🔗 References

  • VisuAlgo - Selection Sort
  • Selection Sort Algorithm Explained
  • Comments (0)

    0/1000 characters
    Loading comments...