Bubble Sort—Test Suite should demonstrate tests on arrays of size 10 § ExampleIn
ID: 3822293 • Letter: B
Question
Bubble Sort—Test Suite should demonstrate tests on arrays of size 10 § ExampleInput: 37110115628910455 § Expected Output: 1, 2, 3, 5, 7, 10, 11, 56, 89, 1045 (15 pts) (5 pts for the algorithm and 10 pts for the code/test cases) The bubble sort is another technique for sorting an array. A bubble sort compares adjacent array elements and exchanges their values if they’re out of order. In this way, the smaller values “bubble” to the top of the array. After the first pass of the bubble sort, the last array element is in the correct position; after the second, the last two items are correctly placed, and so on. Thus, after each pass, the unsorted portion of the array contains 1 less element. Write and test a function that implements this sorting method. Your function should work for arrays of any valid size up a max of 100.C++
Explanation / Answer
#include <iostream>
using namespace std;
void bubbleSort(int a[], int n) {
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(a[j-1] > a[j]){
//swap the elements!
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
}
int main()
{
int a[10] = {5,4,3,1,2,9,8,10,6,7};
bubbleSort(a, 10);
cout<<"Array elements are after sorting: "<<endl;
for(int i=0; i<10; i++){
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Array elements are after sorting:
1 2 3 4 5 6 7 8 9 10
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.