Select Sort
#include <iostream> using namespace std; /* * Program to read a list of integers from standard input and print them in * sorted order. This uses a simple select sort to perform the sort. */ /* * Exchange the arguments. */ void swap(int &a, int &b) { int tmp; // Exchange temp value. tmp = a; a = b; b = tmp; } /* * Select sort. It takes a pointer to the data and the size, * and it sorts the data. */ void sort(int data[], int size) { // Double loop goes through each array position // (each loc value), and checks every later position (scan), // swapping it into loc if it is smaller. That moves the // smallest value to the first position, second smallest to // the second, etc. until the array is sorted. for(int loc = 0; loc < size-1; ++loc) { // Scan everything to the right of loc. for(int scan = loc+1; scan < size; ++scan) { // If value smaller, swap into loc. if(data[loc] > data[scan]) swap(data[loc], data[scan]); } } } /* * Main program. Reads the integers into an array, sorts them, and * prints them out. */ const int MAX_NUM_INTS = 100; int main() { int ints[MAX_NUM_INTS]; // Where the numbers go. // Read them in. Make sure not to read out of bounds. int i; cout << "Please enter some integers to sort: " << endl; for(i = 0; i < MAX_NUM_INTS && cin >> ints[i]; ++i); int numints = i; // Sort them. sort(ints, numints); // Print them. cout << "==================" << endl; for(int i = 0; i < numints; ++i) cout << ints[i] << " "; cout << "\n==================" << endl; }

Notice the parameters to the sort function: the array and its size are passed by two separate parameters.