-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBubble.cpp
77 lines (64 loc) · 1.58 KB
/
Bubble.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
#include <iostream>
using namespace std;
void printArray();
void swap(int a, int b);
void bubbleSort();
const int arrSize = 10;
int arr[arrSize];
int main()
{
// Filling the array with random numbers...
for (int i = 0; i < arrSize; i++)
arr[i] = rand() % 100;
cout << "Array Before Sorting:\n";
printArray();
cout << "\nSorting...\n";
bubbleSort();
cout << "\nArray After Sorting:\n";
printArray();
return 0;
}
void printArray()
{
for (int i = 0; i < arrSize; i++)
cout << arr[i] << "\t";
cout << "\n";
}
void swap(int a, int b)
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
void bubbleSort()
{
/**
* The lastIndex represents: the LAST UNSORTED ELEMENT in the array.
*/
int lastIndex = arrSize - 1;
/**
* This while loop continues as long as lastIndex is greater than 0.
* (If the lastIndex equals to 0, it means that the array is sorted.)
*/
while (lastIndex > 0)
{
/**
* This for loop iterates over the array from the first element to the lastIndex element.
*/
for (int i = 0; i < lastIndex; i++)
{
/**
* If the current element is greater than the next one,
* swap their positions to move the greater one to the right "bubble up".
*/
if (arr[i] > arr[i + 1])
swap(i, i + 1);
}
/**
* This line decreases the value of lastIndex by 1 after each pass through the array.
* This is because after each pass, the largest element is "bubbled" to the end of the array,
* so there's no need to consider it in the next pass.
*/
lastIndex--;
}
}