Skip to content

Array Element SwapΒΆ

Prerequisites: Arrays, Variables

Learning ObjectivesΒΆ

  • Swap two elements in an array correctly.
  • Validate index boundaries before swapping.
  • Understand how swapping is used in sorting logic.

Concept ExplanationΒΆ

Array swapping exchanges values at two indexes. This operation appears in sorting algorithms, partitioning, and rearrangement tasks.

AlgorithmΒΆ

  1. Read array and two indexes i, j.
  2. Validate 0 <= i < n and 0 <= j < n.
  3. Store arr[i] in temp.
  4. Assign arr[i] = arr[j].
  5. Assign arr[j] = temp.

ExampleΒΆ

Input array: [10, 20, 30, 40], i=1, j=3
Output array: [10, 40, 30, 20]

Common MistakesΒΆ

  • Not checking negative/out-of-range indexes.
  • Accidentally swapping same index and expecting change.
  • Using wrong order of assignments without temp.

Practice TasksΒΆ

  1. Swap first and last elements.
  2. Swap all adjacent pairs in a loop.
  3. Write a function swap(arr, i, j) and reuse it in sort logic.

SummaryΒΆ

Correct index handling is as important as swap logic.