Sorting Arrays
When working with arrays, it is often necessary to sort the elements in a particular order. Sorting an array involves rearranging its elements in increasing or decreasing order based on a key value. There are various algorithms available for sorting arrays, each with its own advantages and disadvantages.
Bubble Sort
One of the simplest sorting algorithms is the Bubble Sort. This algorithm repeatedly compares adjacent elements and swaps them if they are in the wrong order. The process is repeated for each pair of adjacent elements until the array is sorted.
Here's an example of the Bubble Sort algorithm implemented in C++:
1#include <iostream>
2using namespace std;
3
4void bubbleSort(int arr[], int n) {
5 for (int i = 0; i < n-1; i++) {
6 for (int j = 0; j < n-i-1; j++) {
7 if (arr[j] > arr[j+1]) {
8 // Swap arr[j] and arr[j+1]
9 int temp = arr[j];
10 arr[j] = arr[j+1];
11 arr[j+1] = temp;
12 }
13 }
14 }
15}
16
17int main() {
18 int arr[] = {64, 34, 25, 12, 22, 11, 90};
19 int n = sizeof(arr)/sizeof(arr[0]);
20
21 cout << "Before sorting: ";
22 for (int i = 0; i < n; i++) {
23 cout << arr[i] << " ";
24 }
25
26 bubbleSort(arr, n);
27
28 cout << "\nAfter sorting: ";
29 for (int i = 0; i < n; i++) {
30 cout << arr[i] << " ";
31 }
32
33 return 0;
34}
In this example, we have an array arr
containing some random numbers. We apply the Bubble Sort algorithm to sort the array in ascending order. The output before sorting is [64, 34, 25, 12, 22, 11, 90]
, and after sorting, it becomes [11, 12, 22, 25, 34, 64, 90]
.
Bubble Sort has a time complexity of O(n^2), where n is the number of elements in the array. While it is not the most efficient algorithm for large datasets, it is relatively simple to implement and understand.
Other Sorting Algorithms
Apart from Bubble Sort, there are other popular sorting algorithms like Selection Sort, Insertion Sort, Merge Sort, and Quick Sort, each with its own strengths and weaknesses. These algorithms are more efficient than Bubble Sort for large datasets and are widely used in practice.
When choosing a sorting algorithm, it is important to consider the specific requirements of the problem at hand, such as the size of the dataset, time and space complexity constraints, and the desired order of sorting.
xxxxxxxxxx
}
using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Before sorting: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
bubbleSort(arr, n);
cout << "\nAfter sorting: ";
for (int i = 0; i < n; i++) {