162k views
0 votes
Write a program that sorts an array of 10 integers using bubble sort. In the bubble sort algorithm, 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 (of 10 items). 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.

User Davertron
by
5.3k points

1 Answer

1 vote

Answer:

#include<iostream>

using namespace std;

int main(){

//initialization

int arr1[10] = {2,4,6,1,7,9,0,3,5,8};

int temp;

int size_arr;

//nested for loop

for(int i=0;i<size_arr-1;i++){

for(int j=0;j<size_arr-i-1;j++){

if(arr1[j]>arr1[j+1]){ //compare

//swapping

temp = arr1[j];

arr1[j]=arr1[j+1];

arr1[j+1]=temp;

}

}

}

//display the each element

for(int i=0;i<10;i++){

cout<<arr1[i]<<" ";

}

return 0;

}

Step-by-step explanation:

Create the main function and declare the variable and defining the array with 10 values.

take the nested for loop, nested loop means loop inside another loop.

the outer loop traverse in the array from 0 to size-1.

and inside loop traverse from 0 to size -i-1, because for every cycle of the outer loop the one element is sorted at the end. so, we do not consider the element from the last for every cycle of the outer loop. That's why (size-i-1)

In the bubble sort, the first element compares with the second element and if the first id greater than the second then swap the value. so, for the above algorithm, we take the if statement and it checks the condition if the condition becomes true then the swap algorithm executes.

we take a third variable for swapping. after that, if the outer loop condition false it means all elements will traverse and then the loop will terminate.

and finally, take another for loop and display the output.

User Nyce
by
5.3k points