Skip to content

Commit e53da69

Browse files
CiganOliviuabranhe
authored andcommitted
Refactor bubble_sort
1 parent 93c4ffb commit e53da69

File tree

1 file changed

+74
-41
lines changed

1 file changed

+74
-41
lines changed

algorithms/sorting/bubble_sort.cpp

Lines changed: 74 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -8,47 +8,80 @@
88
// Contributed by: Abhishek Jaiswal
99
// Github: @Abhishek-iiit
1010
//
11-
#include<stdio.h>
12-
#include<iostream>
13-
14-
using namespace std;
15-
16-
void bubbleSort(int arr[], int n)
17-
{
18-
int i, j;
19-
bool changed;
20-
for (i = 0; i < n-1; i++)
21-
{
22-
changed = false;
23-
for (j = 0; j < n-i-1; j++)
24-
{
25-
if (arr[j] > arr[j+1])
26-
{
27-
swap(arr[j],arr[j+1]);
28-
changed = true;
11+
// Refactoring by: Cigan Oliviu David
12+
// Github: @CiganOliviu
13+
//
14+
15+
#include <iostream>
16+
17+
18+
unsigned int readLength() {
19+
20+
unsigned int length;
21+
22+
std::cin >> length;
23+
24+
return length;
25+
}
26+
27+
void readArray(int array[], unsigned int length) {
28+
29+
for (int i = 0; i < length; i++)
30+
std::cin >> array[i];
31+
}
32+
33+
34+
void bubbleSortArray(int array[], unsigned int length) {
35+
36+
bool changed;
37+
38+
length -= 1;
39+
40+
for (int i = 0; i < length; i++) {
41+
42+
changed = false;
43+
44+
for (int j = 0; j < length - i; j++) {
45+
46+
if (array[j] > array[j + 1]) {
47+
48+
std::swap(array[j], array[j+1]);
49+
changed = true;
50+
}
2951
}
30-
}
31-
if (changed == false)
32-
break;
33-
}
34-
}
35-
36-
int main()
37-
{
38-
int n;
39-
cout<<"Input the total size :"<<endl;
40-
cin>>n;
41-
int arr[n];
42-
cout<<"Input the number one-by-one :"<<endl;
43-
for(int i=0;i<n;i++)
44-
{
45-
cin>>arr[i];
46-
}
47-
bubbleSort(arr,n);
48-
cout<<"Sorted array:"<<endl;
49-
for(int i=0;i<n;i++)
50-
{
51-
cout<<arr[i]<<" ";
52-
}
52+
53+
if (changed == false)
54+
return;
55+
}
56+
}
57+
58+
void outputArray(int array[], unsigned int length) {
59+
60+
for (int i = 0; i < length; i++)
61+
std::cout << array[i] << " ";
62+
63+
std::cout << '\n';
64+
}
65+
66+
int main() {
67+
68+
std::cout << "Input the total size : ";
69+
70+
unsigned int length;
71+
72+
length = readLength();
73+
74+
int array[length];
75+
76+
std::cout << "Input the number one-by-one : ";
77+
78+
readArray(array, length);
79+
80+
bubbleSortArray(array, length);
81+
82+
std::cout << "Sorted array:" << std::endl;
83+
84+
outputArray(array, length);
85+
5386
return 0;
5487
}

0 commit comments

Comments
 (0)