Answer:
//Here is code in C++.
//include header
#include <bits/stdc++.h>
using namespace std;
// function to print the array
void out_arr(int inp[], int len)
{
for (int i = 0; i < len; i++)
cout << inp[i] << " ";
cout << endl;
}
// main function
int main()
{
// decalare and initialize the array
int inp[] = {9,8,7,6,5,4,3,2,1};
//find the length of array
int len = sizeof(inp)/sizeof(inp[0]);
int x, y;
// perform bubble sort, only 3 pass
for (x = 0; x < 3; x++)
{
for (y= 0; y< len-x-1; y++)
if (inp[y] > inp[y+1])
{
int t=inp[y];
inp[y]=inp[y+1];
inp[y+1]=t;
}
cout<<"array after "<<x+1<<" pass"<<endl;
// print the array after every pass
out_arr(inp, len);
}
return 0;
}
Step-by-step explanation:
Declare an integer array "inp" and initialize with {9,8,7,6,5,4,3,2,1}. Find the length of the array.In first pass of bubble sort, largest value is placed at the correct position in the array. And in the second, second largest value is placed at its correct position. After the n pass, array will be sorted. In each pass, each element is compared with the next element. if the value is greater than swap them. This continues for all elements in each pass. In the end of a pass a value is placed correctly. So if there is only 3 pass then 3 largest values will be placed at their right place.
Output:
8 7 6 5 4 3 2 1 9
array after 2 pass
7 6 5 4 3 2 1 8 9
array after 3 pass
6 5 4 3 2 1 7 8 9