Understanding Insertion Sort
Sort nums into nondecreasing order in place and return the modified array.
How it works
Grow a sorted prefix by shifting larger values to make room for the next value.
Treat the first value as an already sorted prefix. Save the next value and shift larger prefix entries right. Place the saved value in the resulting gap.
Try an example
Input: nums = [5, 2, 4, 6, 1, 3]
Output: [1, 2, 3, 4, 5, 6]
Grow a sorted prefix by shifting larger values to make room for the next value.
Constraints
- 0–32 integers between -1,000,000 and 1,000,000.
- Duplicates and negative values are allowed.
Use the simulator
Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.
Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.