-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbubble_sort.cpp
103 lines (88 loc) · 1.64 KB
/
bubble_sort.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*******
* Sun 05 Mar 2017 08:21:03 PM BDT
********/
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
void create_array(int *&A, int s);
void populate_array(int *A, int s, int l, int h);
void display_array(int *A, int s);
int max_value(int *A, int s);
int max_dig(int dig);
void swap(int &, int &);
void bubble_sort(int *A, int s);
void selection_sort(int *A, int s);
int main()
{
int *A, n;
int h, l;
int key;
cout << "Bubble Sort\n";
n = 100;
h = 10;
l = 100;
create_array(A, n);
populate_array(A, n, h, l);
display_array(A, n);
bubble_sort(A, n);
display_array(A, n);
return 0;
}
void create_array(int *&A, int s)
{
A = new int[s];
}
void populate_array(int *A, int s, int l, int h)
{
srand(time(NULL));
for (int i = 0; i < s; ++i)
{
A[i] = l + rand() % (h + 1 - l);
}
}
int max_value(int *A, int s)
{
int mx = A[0];
for (int i = 1; i < s; ++i)
{
if (A[i] > mx)
mx = A[i];
}
return mx;
}
int max_dig(int dig)
{
if (dig < 10)
return 1;
return 1 + max_dig(dig / 10);
}
void display_array(int *A, int s)
{
cout << endl;
for (int i = 0; i < s; ++i)
{
if (i % 15 == 0)
cout << endl;
cout << setw(max_dig(max_value(A, s)) + 2) << A[i];
}
cout << endl;
}
void swap(int &a, int &b)
{
int t = a;
a = b;
b = t;
}
void bubble_sort(int *A, int s)
{
for (int i = 0; i < s; ++i)
{
for (int j = 0; j < s - i; ++j)
{
if (A[j] > A[j + 1])
swap(A[j], A[j + 1]);
}
}
}