selectionSort.definition

selectionSort.descriptionPart1

selectionSort.descriptionPart2

selectionSort.keyPointsTitle

  • selectionSort.keyPoint1
  • selectionSort.keyPoint2
  • selectionSort.keyPoint3
  • selectionSort.keyPoint4

selectionSort.exampleTitle

Start:
6425122211
Pass 1:
1125122264
Sorted:
1112222564

selectionSort.syntaxTitle

// Java
public static void selectionSort(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
        int minIdx = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIdx]) {
                minIdx = j;
            }
        }
        // Swap arr[i] and arr[minIdx]
        int temp = arr[minIdx];
        arr[minIdx] = arr[i];
        arr[i] = temp;
    }
}
# Python
def selection_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        min_idx = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr
// C++
void selectionSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int minIdx = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIdx])
                minIdx = j;
        }
        swap(arr[i], arr[minIdx]);
    }
}
// JavaScript
function selectionSort(arr) {
  const n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    let minIdx = i;
    for (let j = i + 1; j < n; j++) {
      if (arr[j] < arr[minIdx]) {
        minIdx = j;
      }
    }
    [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
  }
  return arr;
}

Interactive Selection Sort Visualization

📊

Enter numbers above and click "Create Array" to begin.

Pass: 0Comparisons: 0Elements: 0
Idle
Current (i)
Scanning
Min Index
Swapping
Sorted

Note: Selection Sort finds the minimum element in the unsorted portion and swaps it with the first unsorted element. Always performs O(n²) comparisons regardless of input order.

Time & Space Complexity

CaseComplexityDescription
Best CaseO(n²)Always scans entire unsorted portion (no early exit)
Average CaseO(n²)Same as best/worst case - always makes n(n-1)/2 comparisons
Worst CaseO(n²)Array in reverse order still requires same comparisons
SpaceO(1)In-place sorting, only uses a few variables

Comparisons: Selection Sort always makes exactly n(n-1)/2 comparisons.

Swaps: Makes at most n-1 swaps (one per pass), fewer than Bubble Sort.

Stability: Not stable by default - equal elements may change relative order.

enhanced.relatedTopics.prerequisites

enhanced.relatedTopics.related

enhanced.relatedTopics.advanced

selectionSort.continueLearning

enhanced.author.title

enhanced.author.writtenBy:enhanced.author.teamName
enhanced.author.reviewedBy:enhanced.author.reviewerName
enhanced.author.lastUpdated:January 29, 2026