Algorithm
Code Examples
#1 Optimized Bubble Sort in Python
Code -
Python Programming
def optimized_bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Set a flag to optimize by checking if any swapping occurs in the inner loop
swapped = False
# Last i elements are already sorted, so no need to check them
for j in range(0, n-i-1):
# Swap if the element found is greater than the next element
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
# If no swapping occurred in the inner loop, the array is already sorted
if not swapped:
break
# Example usage:
my_list = [64, 34, 25, 12, 22, 11, 90]
optimized_bubble_sort(my_list)
print("Sorted array:", my_list)
Copy The Code &
Try With Live Editor
#2 Optimized Bubble Sort in Java
Code -
Java Programming
public class BubbleSort {
public static void main(String[] args) {
int[] array = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Original Array:");
printArray(array);
// Apply the optimized bubble sort
bubbleSort(array);
System.out.println("\nSorted Array:");
printArray(array);
}
static void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// If no two elements were swapped in the inner loop, the array is already sorted
if (!swapped) {
break;
}
}
}
static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
}
Copy The Code &
Try With Live Editor
#3 Optimized Bubble Sort in C
Code -
C Programming
#include <stdio.h>
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void optimizedBubbleSort(int arr[], int n) {
int i, j;
int swapped;
for (i = 0; i < n-1; i++) {
swapped = 0; // Flag to check if any swapping occurred in this pass
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
swap(&arr[j], &arr[j+1]);
swapped = 1; // Set the flag to indicate swapping occurred
}
}
// If no two elements were swapped by inner loop, the array is sorted
if (swapped == 0) {
break;
}
}
}
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);
optimizedBubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Copy The Code &
Try With Live Editor
#4 Optimized Bubble Sort in C++
Code -
C++ Programming
start coding...
Copy The Code &
Try With Live Editor