In: Computer Science
C++
Bubble Sort
Write a program that ask user to enter 7 numbers and store that in array. Display that all numbers before and after performing Bubble sort. You must have to create new function with required parameter to perform Bubble sort.
Sample Run :-
Enter 1 number :- 1
Enter 2 number :- 5
Enter 3 number :- 7
Enter 4 number :- 45
Enter 5 number :- 90
Enter 6 number :- 6
Enter 7 number :- 55
Numbers Before Bubble Sort :-
1 5 7 45 90 6 55
Numbers after Bubble sort :- 1 5 6 7 45 55 90
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
// To sort in descending order, change > to < in this line.
if (arr[j] > arr[j + 1]) {
// swap if greater is at the rear position
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[7];
for(int i=0;i<7;i++)
{
cout<<"Enter "<<i+1<<" number:- ";
cin>>arr[i];
}
cout<<"Numbers Before Bubble Sort:- ";
for(int i=0;i<7;i++)
{
cout<<arr[i]<<" ";
}
bubbleSort(arr,7);
cout<<"\nNumbers After Bubble Sort:- ";
for(int i=0;i<7;i++)
{
cout<<arr[i]<<" ";
}
}