2. Sorting Arrays There are several sorting algorithms that can be used to sort
ID: 3819421 • Letter: 2
Question
2. Sorting Arrays There are several sorting algorithms that can be used to sort arrays. The bubble sort is a fairly simple sorting algorithm. As elements are sorted in the bubble sort, they gradually "bubble" (or rise) to their proper location in the array, like bubbles rising in a glass of soda. The following program uses the bubble sort algorithm to sort integers in an array in ascending order. Note that this program uses the range-based for loop in C++11. sorts an array of integers using Bubble Sort ainclude ejostreamo using namespace std const int SIZE 10 void bubble sortint arrll, int length): int main() int arr ISIZEJ for (int i m i SIZE: i++) cout "Enter an integer: arr[i]: cin bubble sort (arr, SIZE): for (int a arr) cout a cout end return void bubblesort(int arrlj, int length) bubble largest number toward the right for (int i length 1: i 0: i--) for (int j a j i j++) if (arr [i] arr [j+1]) swap the numbers int temp m arr arr tempiExplanation / Answer
#include <iostream>
using namespace std;
const int SIZE = 20; //size changed to 20
void bubblesort(int arr[],int length);
int main()
{
int arr[SIZE];
for(int i = 0;i<SIZE;i++)
{
cout<<" Enter an integer : ";
cin>>arr[i];
}
bubblesort(arr,SIZE);
cout<<endl;
for(int a: arr)
{
cout<<a<<" ";
}
return 0;
}
void bubblesort(int arr[],int length)
{
//bubble smallest number towards the right
for(int i = length - 1;i>0;i--)
{
for(int j= 0; j<i;j++)
{
if(arr[j]<arr[j+1])
{
//swap the numbers
int temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.