2. Sorting Arrays There are several sorting algorithms that can be used to sort
ID: 3819411 • 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 bubblesrising 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 arr int length): int maint) int arr ISIZEJ for (int i 0: i e SIZE: i cout "Enter an integer: cin arr til: bubble sort (arr, SIZE): for (int a arr) cout a "a cout end return e; void bubblesort(int arrti int length) bubble largest number toward the right for (int i length 1: i 0: i--) for (int j a: j i j++) if (arrlil arrlj+11) swap the numbers int temp m arr 11: arrlij 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:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str1[12],str2[12];
int length1,length2;
strcpy(str1,"Programming");
cout<<" Enter the word "Programming" at the prompt";
cin.getline(str2,12);
length1 = strlen(str1);
length2 = strlen(str2);
if(length1 == length2)
{
cout<<" They have the same lengths , but are they the same?";
}
if(strcmp(str1,str2)== 0)
{
cout<<" The two C-strings are the same.";
}
else
{
cout<<" The two C-strings are NOT the same.";
}
return 0;
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.