Bubblesort

An algorithm to sort an array field of integer numbers.

main.cpp
1/*
2
3    bubblesort.cpp
4    
5    How to compile with GCC under LINUX/UNIX:
6    g++ -o bubblesort bubblesort.cpp
7
8*/
9#include <iostream>
10#include <ctime>
11using namespace std;
12
13void randomize();
14void bubblesort(int *, int n);
15void swap(int *, int *);
16void print(int *, int n);
17
18int main(int argc, char **argv) {
19    cout << "Randomizing integer field..." << endl;
20    
21    randomize();
22    
23    return 0;
24}
25
26void randomize() {
27    int num;
28    cout << "How much numbers do you want to generate?: ";
29    cin >> num;
30    
31    int *field = new int[num];
32    srand(time(0));
33    double time = 0;
34    clock_t start, end;
35    
36    for(int i = 1; i <= num; i++) {
37        field[i] = rand() % 10000;
38    }
39    
40    cout << "Unsorted field of integer numbers:";
41    print(field,num);
42    
43    start = clock();
44    
45    bubblesort(field, num);
46    cout << "Sorted field of integer numbers:";
47    print(field,num);
48    end = clock();
49    time = (time + (end - start)) / CLOCKS_PER_SEC;
50    
51    cout << endl << "Ticks: "<< end-start;
52    cout << endl << "Ticks: " << end-start << ':' <<
53CLOCKS_PER_SEC << endl;
54    cout << endl << "Time: " << time << "s" << endl;
55}
56
57void bubblesort(int *field, int n) {
58    int o = n;
59    bool swapped;
60    
61    do {
62        swapped = false;
63        for(int i = 0; i < n; i++) {
64            if(field[i] > field[i + 1]) {
65                swap(field[i], field[i + 1]);
66                swapped = true;
67            }
68            else if(field[i] < field[i + 1]) o--;
69        }
70    } while(o != 0 && swapped);
71}
72
73void swap(int *pos1, int *pos2) {
74    int tmp = *pos1;
75    *pos1 = *pos2;
76    *pos2 = tmp;
77}
78
79void print(int *field, int n) {
80    int counter = 0;
81    cout << endl << endl;
82    for(int i = 1; i <= n; i++) {
83        counter++;
84        cout << field[i] << ", ";
85        
86        if(counter == 5) {
87            cout << endl;
88            counter = 0;
89        }
90        
91    }
92    cout << endl << endl;
93}