Bubble Sort Algorithm
The Bubble Sort Algorithm is a simple and widely-known sorting technique used in computer programming to arrange a list of elements, such as numbers or strings, in a specific order, either ascending or descending. It is named after the process of bubbles rising to the surface in a liquid, as it works by repeatedly stepping through the list and comparing adjacent pairs of elements. If the pair of elements is found to be in the wrong order, they are swapped, effectively "bubbling" the larger element towards the end of the list. This process is repeated until no more swaps are needed, indicating that the list is fully sorted.
Bubble Sort is considered an inefficient algorithm for large datasets due to its high time complexity, which is O(n^2) in the worst and average cases, where n is the number of elements in the list. This means that the algorithm's runtime grows quadratically with the size of the input, making it impractical for extensive lists. However, Bubble Sort has the advantage of being easy to understand and implement, making it suitable for educational purposes or for sorting small datasets where performance is not a critical concern. Furthermore, Bubble Sort is a stable sorting algorithm, meaning that it preserves the relative order of equal elements, which can be a desirable property in certain applications.
//sorting of array list using bubble sort
#include <stdio.h>
/*Displays the array, passed to this method*/
void display(int arr[], int n){
int i;
for(i = 0; i < n; i++){
printf("%d ", arr[i]);
}
printf("\n");
}
/*Swap function to swap two values*/
void swap(int *first, int *second){
int temp = *first;
*first = *second;
*second = temp;
}
/*This is where the sorting of the array takes place
arr[] --- Array to be sorted
size --- Array Size
*/
void bubbleSort(int arr[], int size){
for(int i=0; i<size-1; i++) {
for(int j=0; j<size-1-i; j++) {
if(arr[j]>arr[j+1]) {
swap(&arr[j], &arr[j+1]);
}
}
}
}
int main(int argc, const char * argv[]) {
int n;
printf("Enter size of array:\n");
scanf("%d", &n); // E.g. 8
printf("Enter the elements of the array\n");
int i;
int arr[n];
for(i = 0; i < n; i++){
scanf("%d", &arr[i] );
}
printf("Original array: ");
display(arr, n); // Original array : 10 11 9 8 4 7 3 8
bubbleSort(arr, n);
printf("Sorted array: ");
display(arr, n); // Sorted array : 3 4 7 8 8 9 10 11
return 0;
}