bubble sort in c+
Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. Here is an example of bubble sort implementation in C++:
#include <iostream>
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]) {
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]);
bubbleSort(arr, n);
cout << "Sorted array: \n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Explanation for each step:
The
bubbleSort
function takes two parameters: an arrayarr
and its sizen
.The outer loop
for (int i = 0; i < n - 1; i++)
runs from the first element of the array to the second-to-last element. It represents the number of passes through the list.The inner loop
for (int j = 0; j < n - i - 1; j++)
runs from the first element to the last unsorted element of the array. It compares adjacent elements and swaps them if they are in the wrong order.Inside the inner loop, the
if (arr[j] > arr[j + 1])
condition checks if the current element is greater than the next element. If it is, a swap is performed using a temporary variabletemp
.After the inner loop completes for each pass, the largest element of the unsorted part of the array "bubbles" up to its correct position.
This process continues until the entire array is sorted.
The
main
function initializes an arrayarr
, calculates its sizen
, calls thebubbleSort
function, and then prints the sorted array.The sorted array is printed using the
cout
statement inside thefor
loop.Finally, the
main
function returns 0, indicating successful execution of the program.