Skip to content

[Bug]: Quick Sort swap step message shows wrong value after destructuring swap #749

Description

@vipul674

Summary

In quickSortSteps.js, the swap step inside performPartition reads arr[j] after the destructuring swap mutates the array. The message shows the old arr[i] value (already placed from a previous iteration) instead of the current element that was actually smaller than the pivot.

Steps to reproduce

  1. Open AlgoScope and navigate to Quick Sort.
  2. Generate an array and start the visualization.
  3. Watch the swap step messages during partitioning — the value highlighted as "smaller than pivot" is incorrect when i !== j.

Expected behavior

The message should show the element that was detected as smaller than the pivot and is being moved to the left partition.

Actual behavior

Because the destructuring swap [arr[i], arr[j]] = [arr[j], arr[i]] executes before the message template reads arr[j], the message reads the replaced value at index j (the old arr[i] from a previous pass) instead of the current element being moved.

// Current code (broken — swap before message)
[arr[i], arr[j]] = [arr[j], arr[i]]
steps.push(createStep({
  message: `${arr[j]} is smaller than pivot, move it to index ${i}.`,  // arr[j] is now old arr[i]!
  ...
}))

Fix

Capture the pre-swap value before the destructuring:

const smallerValue = arr[j]
;[arr[i], arr[j]] = [arr[j], arr[i]]
steps.push(createStep({
  message: `${smallerValue} is smaller than pivot, move it to index ${i}.`,
  ...
}))

File

src/algorithms/sorting/quickSortSteps.js — inside performPartition(), around line 135.

Operating system

Any

AlgoScope version

1.13.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions