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.