// This program uses the bubble sort algorithm to sort an // array in ascending order. #include using namespace std; // Function prototypes void sortArray(int [], int); void showArray(int [], int); int main() { // Array of unsorted values int n; cout << "Bubble Sort Algorithm \nHow big an array would you like? "; cin >> n; int values[n]; for(int i = 0; i < n; i++) values[i] = rand()%n; // Display the values. cout << "The unsorted values are:\n"; showArray(values, n); // Sort the values. sortArray(values, n); // Display them again. cout << "The sorted values are:\n"; showArray(values, n); system("pause"); } //*********************************************************** // Definition of function sortArray * // This function performs an ascending order bubble sort on * // array. size is the number of elements in the array. * //*********************************************************** void sortArray(int array[], int size) { bool swap; int temp; do { swap = false; for (int count = 0; count < (size - 1); count++) { if (array[count] > array[count + 1]) { temp = array[count]; array[count] = array[count + 1]; array[count + 1] = temp; swap = true; } } } while (swap); } //************************************************************* // Definition of function showArray. * // This function displays the contents of array. size is the * // number of elements. * //************************************************************* void showArray(int array[], int size) { for (int count = 0; count < size; count++) cout << array[count] << " "; cout << endl; }