Skip to content

Commit 5ea79dd

Browse files
authored
Add bubble_sort
1 parent 6e16ca8 commit 5ea79dd

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

src/bubble_sort.cpp

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#include <iostream>
2+
#include <string>
3+
4+
#define SIZE 10
5+
6+
// Function prototypes
7+
void printArray(int array[]);
8+
void bubbleSort(int array[SIZE]);
9+
10+
/**
11+
* @brief Main function that demonstrates the sorting algorithm.
12+
*
13+
* Initializes an array of integers, prints it, sorts it using the bubble sort
14+
* algorithm, and prints the sorted array.
15+
*
16+
* @return int Status code (0 for success)
17+
*/
18+
19+
int main()
20+
{
21+
// Initialize an array of integers in descending order
22+
int array[SIZE]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
23+
24+
// Print the original array
25+
printArray(array);
26+
std::cout << std::endl;
27+
28+
// Sort the array using bubble sort
29+
bubbleSort(array);
30+
31+
// Print the sorted array
32+
printArray(array);
33+
34+
std::cout << std::endl;
35+
system("PAUSE");
36+
return 0;
37+
}
38+
39+
/**
40+
* @brief Prints the elements of an integer array.
41+
*
42+
* This function takes an array of integers and prints each element separated
43+
* by a pipe ('|') for easy readability.
44+
*
45+
* @param array The integer array to be printed
46+
*/
47+
48+
void printArray(int array[])
49+
{
50+
for (int i = 0; i < SIZE; ++i)
51+
{
52+
std::cout << " |" << array[i] << "| ";
53+
}
54+
}
55+
56+
/**
57+
* @brief Sorts an array using the Bubble Sort algorithm.
58+
*
59+
* This function sorts an array of integers in ascending order using the bubble
60+
* sort algorithm. The algorithm repeatedly steps through the list, compares
61+
* adjacent elements, and swaps them if they are in the wrong order.
62+
*
63+
* @param array The integer array to be sorted
64+
*/
65+
66+
void bubbleSort(int array[SIZE])
67+
{
68+
int temp; // Temporary variable for swapping
69+
70+
// Outer loop to control the number of passes
71+
for (int i = 0; i < SIZE - 1; i++)
72+
{
73+
// Inner loop to compare adjacent elements
74+
for (int j = 0; j < SIZE - 1 - i; j++)
75+
{
76+
// If the current element is greater than the next, swap them
77+
if (array[j] > array[j + 1])
78+
{
79+
temp = array[j];
80+
array[j] = array[j + 1];
81+
array[j + 1] = temp;
82+
}
83+
}
84+
}
85+
}

0 commit comments

Comments
 (0)