The Playing Cards Sort

EasyAcc. 94.4%
+20 XP 8

The Playing Cards (Insertion)

Have you ever sorted a hand of playing cards? You pick one card at a time and "insert" it into its correct relative position among the cards you already hold. This is exactly how Insertion Sort works!

The Assignment

Your mission is to insert elements into their sorted slots. Your function receives data.

  1. Iterate from index 1 to the end of the array.
  2. Store the current value in a variable named key.
  3. "Step backward" through the sorted part of the array (to the left of i).
  4. Shift every element that is greater than key one position to the right to make a hole.
  5. Place key into the empty hole.
  6. Print the final sorted result (space-separated).

01EXAMPLE 1

Input[12, 11, 13, 5, 6]
Output5 6 11 12 13

Explanation: Each element inserted into sorted prefix.

Constraints

  • Efficient for nearly sorted data.
AlgorithmsSorting
JavaScript
Loading...
1 Hidden

Input Arguments

data[12,11,13,5,6]

Expected Output

5 6 11 12 13

Click RUN to test your solution