Bubble 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 bubble sort to perform the sorting. */ /* * Exchange the arguments. */ void swap(int &a, int &b) { int tmp; // Exchange temp value. tmp = a; a = b; b = tmp; } /* * Bubble sort. It takes a pointer to the start of the data, and an * end pointer (one past the end of the data) and sorts it. */ void sort(int *data, int *end) { // Scan through the array. Like the select sort, the smallest // item to the right of loc is brought into the loc position. // The inner loop examines pairs starting from the right, and // and swaps them when out of order. This scan will pick up // the smallest item and eventually drag it back to loc. This // loop also remembers if any items have been swapped, since // a swap-less scan means all the data are in order, so we // can stop. for(int *loc = data; loc < end-1; ++loc) { // Scan the items right of loc, starting from the right, // swapping any pairs which are out of order. bool swapped = false; for(int *swapper = end-1; swapper > loc; --swapper) { // If out of order, exchange. if(swapper[0] < swapper[-1]) { swap(swapper[0], swapper[-1]); swapped = true; } } if(!swapped) break; } } /* * 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. cout << "Please enter some integers to sort: " << endl; int *scan, *end = ints + MAX_NUM_INTS; for(scan = ints; scan < end && cin >> *scan; ++scan); // Sort them. Note that scan points one past the last valid // data item, which is what is needed. sort(ints, scan); // Print them. cout << "==================" << endl; for(int *p = ints; p < scan; ++p) cout << *p << " "; cout << "\n==================" << endl; }

Notice the parameters to the sort function: A pointer to the beginning, and a pointer to the slot after the data in the array. This is also a common way to pass arrays to functions.