Write a program that asks the user to type 10 integers that will be stored in an array. The program must sort the array in ascending order and must display the array.
Suggested algorithm:
We look for the index of the smallest element among the indices from 0 to 9 and we exchange this element with t [0].
We look for the index of the smallest element among the indices from 1 to 9 and we exchange this element with t [1].
We look for the index of the smallest element among the indices from 2 to 9 and we exchange this element with t [2].
We look for the index of the smallest element among the indices of 8 to 9 and we exchange this element with t [8].
The purpose of this exercise is to check the following technical points:
Simple use of arrays.
A simple algorithm on an array: sorting an array.
Here is the source file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
#include <iostream> using namespace std; int main() { const int size = 10; int table[size]; int buffer; for(int i = 0; i < size; i++) // Fill in the table { cout << "What value has the index " << i << " : "; cin >> table[i]; } int j = 0; while(j < size) // Main Loop { int index = j; for(int i = j; i < size - 1; i++) // Search loop of the smallest element { if(table[index] > table[i + 1]) index = i + 1; } // We reverse the elements buffer = table[j]; table[j] = table[index]; table[index] = buffer; j++; } // We display the sorted table for(int i = 0; i < size; i++) cout << "Index " << i << " : " << table[i] << endl; return 0; } |
Output: