Sorting Algorithms
In the world of programming, sorting algorithms play a crucial role in organizing data efficiently. Sorting algorithms allow us to rearrange elements in a specific order, which simplifies searching, analyzing, and manipulating data.
There are various sorting algorithms available, each with its strengths and weaknesses. Let's explore a simple and commonly used sorting algorithm called Bubble Sort.
Bubble Sort works by repeatedly swapping adjacent elements if they are in the wrong order. The algorithm iterates through the entire array multiple times until all elements are in the correct order.
Here's an example of Bubble Sort implemented in C++:
TEXT/X-C++SRC
1#include <iostream>
2#include <vector>
3
4void bubbleSort(std::vector<int>& arr) {
5 int n = arr.size();
6 bool swapped;
7 for (int i = 0; i < n-1; i++) {
8 swapped = false;
9 for (int j = 0; j < n-1-i; j++) {
10 if (arr[j] > arr[j+1]) {
11 std::swap(arr[j], arr[j+1]);
12 swapped = true;
13 }
14 }
15 if (!swapped) {
16 break;
17 }
18 }
19}
20
21void printArray(const std::vector<int>& arr) {
22 for (int i : arr) {
23 std::cout << i << " ";
24 }
25 std::cout << std::endl;
26}
27
28int main() {
29 std::vector<int> arr = {5, 2, 4, 6, 1, 3};
30 std::cout << "Original Array: ";
31 printArray(arr);
32
33 bubbleSort(arr);
34 std::cout << "Sorted Array (using Bubble Sort): ";
35 printArray(arr);
36
37 return 0;
38}
xxxxxxxxxx
38
}
void bubbleSort(std::vector<int>& arr) {
int n = arr.size();
bool swapped;
for (int i = 0; i < n-1; i++) {
swapped = false;
for (int j = 0; j < n-1-i; j++) {
if (arr[j] > arr[j+1]) {
std::swap(arr[j], arr[j+1]);
swapped = true;
}
}
if (!swapped) {
break;
}
}
}
void printArray(const std::vector<int>& arr) {
for (int i : arr) {
std::cout << i << " ";
}
std::cout << std::endl;
}
int main() {
std::vector<int> arr = {5, 2, 4, 6, 1, 3};
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment