Write me a bubble sort in C++.
- User
Write me a bubble sort in C++.
Assistant
Sure, here is the bubble sort algorithm in C++:
void bubbleSort(int arr[], int n) { // loop through the array, comparing adjacent elements for (int i = 0; i < n - 1; i++) { // if the current element is greater than the next element, swap them if (arr[i] > arr[i + 1]) { int temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } } }This algorithm works by repeatedly comparing adjacent elements in the array. If the current element is greater than the next element, the two elements are swapped. This process continues until no more swaps are needed, which means that the array is sorted.
Here is an example of how to use the bubble sort algorithm:
int main() { // declare an array of integers int arr[] = {5, 1, 4, 2, 3}; // get the size of the array int n = sizeof(arr) / sizeof(arr[0]); // sort the array bubbleSort(arr, n); // print the sorted array for (int i = 0; i < n; i++) { cout << arr[i] << " "; } return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.