Bubble Sort
Bubble Sort
Bubble Sort
Due to its simplicity, bubble sort is often used to introduce the concept
of a sorting algorithm. In computer graphics, it is popular for its
capability to detect a tiny error (like a swap of just two elements) in
almost-sorted arrays and fix it with just linear complexity (2n).
Bubble Sort Algorithm:
In this algorithm:
• Traverse from left and compare adjacent elements and the higher one
is placed at right side.
• In this way, the largest element is moved to the rightmost end at first.
• This process is then continued to find the second largest and place it
and so on until the data is sorted.
Input: arr[] = {6, 3, 0, 5}
• First Pass:
• The largest element is placed in its correct position, i.e., the end of the
array.
• Time Complexity Analysis of Bubble Sort:
• Best Case: The best case occurs when the array is already sorted. So
the number of comparisons required is N-1 and the number of swaps
required = 0. Hence the best case complexity is O(N).
• Worst Case: The worst-case condition for bubble sort occurs when
elements of the array are arranged in decreasing order.
In the worst case, the total number of iterations or passes required to
sort a given array is (N-1). where ‘N’ is the number of elements
present in the array.
• Average Case : The number of comparisons is constant in Bubble Sort.
So in average case, there are O(N2) comparisons. This is because
irrespective of the arrangement of elements, the number of
comparisons C(N) is same.
• Auxiliary Space: O(1) as no additional space is used.
• Advantages of Bubble Sort:
• Bubble sort is easy to understand and implement.
• It does not require any additional memory space.
• It is a stable sorting algorithm, meaning that elements with the same
key value maintain their relative order in the sorted output.
• Disadvantages of Bubble Sort:
• Bubble sort has a time complexity of O(N2) which makes it very slow
for large data sets.
• Bubble sort is a comparison-based sorting algorithm, which means
that it requires a comparison operator to determine the relative order
of elements in the input data set. It can limit the efficiency of the
algorithm in certain cases.
void swap(int* xp, int* yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bubbleSort(int arr[], int n) {
int i, j;
bool swapped;
for (i = 0; i < n - 1; i++) {
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
swapped = true;
}
}
if (swapped == false)
break;
}
}
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
}
int main() {
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}