previous | index

Testing Selection Sort

#include <stdlib.h>
#include <iostream>
#include <iomanip>
using namespace std;

const int SIZE = 10;

/*
 *  Sorts an array, using the selection sort algorithm.
 *  "v" is the array to sort.
 */
void selectionSort(int v[]) {

  int indexOfLargest, temp;
    
  for (int n = SIZE-1; n > 0; n--) {

    indexOfLargest = 0;           // set up the inner loop

    for (int i = 1; i <= n; i++) {        // find index of largest element
      if ( v[i] > v[indexOfLargest] ) {   // in unsorted part of the array
        indexOfLargest = i;
      }           
    }

    temp = v[n];               // swap the highest position of the unsorted
    v[n] = v[indexOfLargest];  // part with the largest element
    v[indexOfLargest] = temp;
  }  

}

/*
 * This tests selection sort.
 */
int main(int argc, char** argv) {

  int v[SIZE];

  for (int i = 0; i < SIZE; i++) { // Fill the array with random integers
    v[i] = rand() % 100;
  }

  for (int i = 0; i < SIZE; i++) { // Display the unsorted array
    cout << v[i] << "  ";
  }
    
  // Sort v using selection sort
  selectionSort(v);          // carry out the selection sort
    
  cout << endl;
  for (int i = 0; i < SIZE; i++) { // Display the sorted array
    cout << v[i] << "  ";
  }

}
Output:
      83  86  77  15  93  35  86  92  49  21  
      15  21  35  49  77  83  86  86  92  93
	

previous | index