Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Question

Improve the Efficiency of Bubble Sort in C++

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list to be sorted,
compares adjacent items, and swaps them if they are in the wrong order. The pass through the
list is repeated until the list is sorted. However, this algorithm is not very efficient for large
datasets due to its O(n²) time complexity in the worst case.

Given the following basic implementation of Bubble Sort in C++:

#include <iostream>
using namespace std;

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout << "Sorted array: \n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}

Task:

1. Identify and explain one inefficiency in the given Bubble Sort implementation.
2. Modify the provided C++ code to improve the efficiency of the Bubble Sort algorithm by
incorporating a simple optimization.

You might also like