(bubble sort)smaller values gradually “bubble” their way upward to the top of the array like air bubbles rising in water, while the larger values sink to the bottom. The bubble sort makes several passes through the array. On each pass, successive pairs of elements are compared. If a pair is in increasing order (or the values are identical), we leave the values as they are. If a pair is in decreasing order, their values are swapped in the array. The comparisons on each pass proceed as follows the 0th element value is compared to the 1st, the 1st is compared to the 2nd, the 2nd is compared to the third, the second-to-last element is compared to the last element. Write a function named bubblesort that accepts the unsorted array and the size as its parameter. The bubblesort function
sorts an array of 10 integers.Call the function in the main program with array argument and size to test its correctness. Note that the top of the array is the first element at index 0 and the bottom of the array is at index size-1
#include <iostream>
using namespace std;
void bubbleSort(int numbers[], int size) {
for(int i = 0; i<size; i++) {
for(int j = i+1; j<size; j++)
{
if(numbers[j] < numbers[i]) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
}
void displayArray(int numbers[], int size) {
for (int i = 0; i < size; ++i) {
cout << numbers[i]<< " ";
}
cout << "\n";
}
int main() {
int numbers[] = {-2, 0, 10, 11, 9,2, 87, 1, 154, 4};
const int size = 10;
bubbleSort(numbers, size);
cout << "Sorted Array in Ascending Order:\n";
displayArray(numbers, size);
system("pause");
return 0;
}
Comments
Leave a comment