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¶
- Read array and two indexes
i,j. - Validate
0 <= i < nand0 <= j < n. - Store
arr[i]intemp. - Assign
arr[i] = arr[j]. - 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¶
- Swap first and last elements.
- Swap all adjacent pairs in a loop.
- Write a function
swap(arr, i, j)and reuse it in sort logic.
Summary¶
Correct index handling is as important as swap logic.