Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

QUESTION – 1

Name: Ranjit Raj


UID: 20BCS9943
Branch: CSE
Subject: Ds Lab

Q.Write a program to implement bubble sort. Given the numbers 7, 1, 4, 12,


67, 33, and 45. How many swaps will be performed to sort these numbers
using the bubble sort?

Code:

#include<iostream>
using namespace std;
void swapping(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void bubbleSort(int *array, int size) {
for(int i = 0; i<size; i++) {
int swaps = 0;
for(int j = 0; j<size-i-1; j++) {
if(array[j] > array[j+1]) {
swapping(array[j], array[j+1]);
swaps = 1;
}}
if(!swaps)
break;
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
bubbleSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}

Output:

How many swaps will be performed to sort these numbers using the bubble
sort?

In Bubble sort, largest element moves to right. So, a swapping is done, when a
smaller element is found on right side.

So to count number of swaps for an element, just count number of elements


on right side which are smaller than it.
So 4 swaps will be done.

You might also like