cs101-notes
  • CS 101 Notes
  • Big O Notation
  • Big O Cheat Sheet
  • Sorting
    • Summary
    • Bubble Sort
    • Selection Sort
    • Insertion Sort
    • Merge Sort
    • Quick Sort
  • Abstract Data Types
    • Linked List
    • Stack
    • Queue
    • Hash Maps
    • Minimum Ordered Heap
Powered by GitBook
On this page

Was this helpful?

  1. Sorting

Selection Sort

PreviousBubble SortNextInsertion Sort

Last updated 5 years ago

Was this helpful?

template <typename eType>
void selectionSort(int vector<eType> arr, int size) {
  int i, j, first, temp;
  for (i = size - 1; i > 0; i--) {
    first = 0;
    for (j = 1; j <= i; j++)
      if (arr[j] > arr[first]) first = j;
    temp = arr[first];
    arr[first] = arr[i];
    arr[i] = temp;
  }
}
template <typename eType>
void selectionSort(vector<eType> arr, int size) {
  int i, j, first, temp;
  for (i = 0; i < size; i++) {
    first = i;
    for (j = i + 1; j < size; j++)
      if (arr[j] < arr[first]) first = j;
    temp = arr[first];

    arr[first] = arr[i];
    arr[i] = temp;
  }
}
Selection Sort Visualization