#Optimized bubble sort def bubble_sort(lst): swapped = True c = 0 while swapped == True: swapped = False for j in range(len(lst)-1): if(lst[j]>lst[j+1]): lst[j], lst[j + 1] = lst[j + 1], lst[j] #swap the elements swapped = True c +=1 return c #sort a list L = [9, 0, 2, 1, 0, 1, 100, -2, 8, 7, 4, 3, 2] bubble_sort(L) print("The sorted list is: ", L)void bubbleSort(int *arr, int n) { for(int i=0; i<n; i++) { bool flag = false; for(int j=0; j<n-i-1; j++) { if(array[j]>array[j+1]) { flag = true; int temp = array[j+1]; array[j+1] = array[j]; array[j] = temp; } } // No Swapping happened, array is sorted if(!flag){ return; } } }#include <iostream> /** * @brief Performs the optimized bubble sort on an array of integers. * @param array The array to be sorted. * @param size The number of elements in the array. */ void optimizedBubbleSort(int array[], int size) { bool isSorted = false; // Keep iterating until the array is sorted while (!isSorted) { isSorted = true; // Perform pairwise comparisons and swaps for (int i = 0; i < size - 1; ++i) { if (array[i] > array[i + 1]) { // Swap the elements if they are out of order int temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; // Set isSorted to false since a swap occurred isSorted = false; } } // Optimization: Exclude the last (already sorted) element from future comparisons --size; } } int main() { int numbers[] = { 5, 2, 8, 1, 9 }; int size = sizeof(numbers) / sizeof(numbers[0]); std::cout << "Before sorting: "; for (int i = 0; i < size; ++i) { std::cout << numbers[i] << " "; } // Call the optimizedBubbleSort function to sort the array optimizedBubbleSort(numbers, size); std::cout << "\nAfter sorting: "; for (int i = 0; i < size; ++i) { std::cout << numbers[i] << " "; } return 0; } function optimizedBubbleSort(array): n = length(array) isSorted = False while not isSorted: isSorted = True for i from 0 to n - 2: if array[i] > array[i+1]: swap(array[i], array[i+1]) isSorted = False return arraydef bubble_sort(lst): for i in range(len(lst)-1): for j in range(len(lst)-1): if(lst[j]>lst[j+1]): lst[j], lst[j + 1] = lst[j + 1], lst[j] #swap the elements #sort a list L = [9, 0, 2, 1, 0, 1, 100, -2, 8, 7, 4, 3, 2] bubble_sort(L) print("The sorted list is: ", L)