forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.cpp
More file actions
87 lines (55 loc) · 1.49 KB
/
bubble_sort.cpp
File metadata and controls
87 lines (55 loc) · 1.49 KB
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
// C++ implementation of Bubble Sort(Optimised Solution).
//
// The All ▲lgorithms Project
//
// https://allalgorithms.com/
// https://github.com/allalgorithms/cpp
//
// Contributed by: Abhishek Jaiswal
// Github: @Abhishek-iiit
//
// Refactoring by: Cigan Oliviu David
// Github: @CiganOliviu
//
#include <iostream>
unsigned int readLength() {
unsigned int length;
std::cin >> length;
return length;
}
void readArray(int array[], unsigned int length) {
for (int i = 0; i < length; i++)
std::cin >> array[i];
}
void bubbleSortArray(int array[], unsigned int length) {
bool changed;
length -= 1;
for (int i = 0; i < length; i++) {
changed = false;
for (int j = 0; j < length - i; j++) {
if (array[j] > array[j + 1]) {
std::swap(array[j], array[j+1]);
changed = true;
}
}
if (changed == false)
return;
}
}
void outputArray(int array[], unsigned int length) {
for (int i = 0; i < length; i++)
std::cout << array[i] << " ";
std::cout << '\n';
}
int main() {
std::cout << "Input the total size : ";
unsigned int length;
length = readLength();
int array[length];
std::cout << "Input the number one-by-one : ";
readArray(array, length);
bubbleSortArray(array, length);
std::cout << "Sorted array:" << std::endl;
outputArray(array, length);
return 0;
}