Demo entry 6717974

Test

   

Submitted by anonymous on Mar 01, 2018 at 09:16
Language: C++. Code size: 615 Bytes.

void selectionSort (int a[], int n) {
  for (int i = n-1; i > 0; i--) {
    // find the max element in the unsorted a[i .. n-1]
    int maxIndex = i; // assume the max is the last element
    // test against elements before i to find the largest
    for (int j = 0; j < i; j++) {
       // if this element is larger, then it is the new max
       if (a[j] > a[maxIndex])
         // found new max; remember its index
         maxIndex = j;
    }
    // maxIndex is the index of the max element, 
    // swap it with the current position
    if (maxIndex != i)
      swap (a[i], a[maxIndex]);
  }
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).