Skip to content

Array Element Swap

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.