Skip to content

Fix (JavaScript) selectionSort example mutating the input array #321

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

stanislaw-grin
Copy link

@stanislaw-grin stanislaw-grin commented Jul 19, 2025

Summary

This PR fixes a small issue in the selectionSort implementation from the JavaScript examples.

The current implementation uses Array.prototype.splice() directly on the input array, which mutates the original array. As a result, the source array becomes empty after sorting, which is likely unintended behavior — especially in educational material.

What was changed

  • Created a shallow copy of the input array using the spread syntax ([...arr]) to avoid mutating the original.
  • Preserved the original logic for clarity and consistency with the rest of the examples.

Before

const sourceArray = [5, 3, 6, 2, 10];
const sortedArray = selectionSort(sourceArray);
console.log(sourceArray); // []

After

const sourceArray = [5, 3, 6, 2, 10];
const sortedArray = selectionSort(sourceArray);
console.log(sourceArray); // [5, 3, 6, 2, 10]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant