Selection Sort in C

Level 5335 keystrokes

Implements selection sort: for each position it finds the smallest remaining element and swaps it into place. Sorting {64, 25, 12, 22, 11} prints 11 12 22 25 64.

C code

// Sorts arr in ascending order using selection sort
1void selectionSort(int arr[], int n) {
// Position i receives the next smallest value; the last one falls into place by itself
2 for (int i = 0; i < n - 1; i++) {
// Assumes the first unsorted element is the minimum
3 int minIdx = i;
// Scans the rest of the unsorted part
4 for (int j = i + 1; j < n; j++) {
// Remembers the index of any smaller element
5 if (arr[j] < arr[minIdx]) minIdx = j;
6 }
// Swaps the minimum into position i (three lines using a temporary)
7 int temp = arr[i];
8 arr[i] = arr[minIdx];
9 arr[minIdx] = temp;
10 }
11}
// Unsorted input array
12int arr[] = {64, 25, 12, 22, 11};
// Sorts the 5 elements in place
13selectionSort(arr, 5);
// Prints 11 12 22 25 64, each value followed by a space
14for (int i = 0; i < 5; i++) printf("%d ", arr[i]);

Output

11 12 22 25 64 
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 14
  • [× 9
  • ]× 9
  • =× 9
  • ,× 7
  • (× 7
  • )× 7
  • +× 7
  • {× 4
  • }× 4

More C examples at level 5

← C typing practice