bubble sort c++
#include <iostream>
using namespace std;
void swap(int xp, int yp) {
int temp = *xp;
xp = yp;
*yp = temp;
}
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], &arr[j+1]);
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout << "Sorted array: ";
for (int i=0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
This C++ program demonstrates the implementation of the bubble sort algorithm. The swap
function exchanges the values of two integer pointers, while the bubbleSort
function sorts an array of integers in ascending order using the bubble sort algorithm. In the main
function, an unsorted array is initialized, and then sorted using the bubbleSort
function. Finally, the sorted array is printed to the console.