Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
Loading...
Searching...
No Matches
bubble_sort.cpp File Reference

Bubble sort algorithm. More...

#include <iostream>
#include <vector>
Include dependency graph for bubble_sort.cpp:

Functions

int main ()
 

Detailed Description

Bubble sort algorithm.

The working principle of the Bubble sort algorithm:

Bubble sort algorithm is the bubble sorting algorithm. The most important reason for calling the bubble is that the largest number is thrown at the end of this algorithm. This is all about the logic. In each iteration, the largest number is expired and when iterations are completed, the sorting takes place.

What is Swap?

Swap in the software means that two variables are displaced. An additional variable is required for this operation. x = 5, y = 10. We want x = 10, y = 5. Here we create the most variable to do it.

int z; z = x; x = y; y = z;

The above process is a typical displacement process. When x assigns the value to x, the old value of x is lost. That's why we created a variable z to create the first value of the value of x, and finally, we have assigned to y.

Bubble Sort Algorithm Analysis (Best Case - Worst Case - Average Case)

Bubble Sort Worst Case Performance is O (n²). Why is that? Because if you remember Big O Notation, we were calculating the complexity of the algorithms in the nested loops. The n * (n - 1) product gives us O (n²) performance. In the worst case all the steps of the cycle will occur. Bubble Sort (Avarage Case) Performance. Bubble Sort is not an optimal algorithm. in average, O (n²) performance is taken. Bubble Sort Best Case Performance. O (n). However, you can't get the best status in the code we shared above. This happens on the optimized bubble sort algorithm. It's right down there.

Function Documentation

◆ main()

int main ( void )
43 {
44 int n;
45 bool swap_check = true;
46 std::cout << "Enter the amount of numbers to sort: ";
47 std::cin >> n;
48 std::vector<int> numbers;
49 std::cout << "Enter " << n << " numbers: ";
50 int num;
51
52 // Input
53 for (int i = 0; i < n; i++) {
54 std::cin >> num;
55 numbers.push_back(num);
56 }
57
58 // Bubble Sorting
59 for (int i = 0; (i < n) && (swap_check); i++) {
60 swap_check = false;
61 for (int j = 0; j < n - 1 - i; j++) {
62 if (numbers[j] > numbers[j + 1]) {
63 swap_check = true;
64 std::swap(numbers[j],
65 numbers[j + 1]); // by changing swap location.
66 // I mean, j. If the number is
67 // greater than j + 1, then it
68 // means the location.
69 }
70 }
71 }
72
73 // Output
74 std::cout << "\nSorted Array : ";
75 for (int i = 0; i < numbers.size(); i++) {
76 if (i != numbers.size() - 1) {
77 std::cout << numbers[i] << ", ";
78 } else {
79 std::cout << numbers[i] << std::endl;
80 }
81 }
82 return 0;
83}
T endl(T... args)
T push_back(T... args)
T size(T... args)
T swap(T... args)