Bubble sort in C
0 269
Bubble sort, a straightforward sorting technique in C, iterates over a list, evaluates neighboring elements, and exchanges them when their order is incorrect.
Introduction:
Bubble sort is one of the simplest sorting algorithms, commonly taught for educational purposes due to its simplicity.
Function Definition:
Bubble sort operates by iteratively traversing the list, examining adjacent elements, and exchanging them if they're out of order.
This process continues until the entire list is sorted.
Characteristics:
Bubble sort has a time complexity of O(n^2), making it inefficient for large datasets.
It is an in-place algorithm, meaning it doesn't require additional memory space for sorting.
Bubble sort is stable, meaning it preserves the relative order of equal elements.
Advantage:
Simplicity: Bubble sort is easy to understand and implement, making it suitable for educational purposes.
Space Efficiency: It doesn't require additional memory space for sorting, as it operates directly on the input array.
Disadvantage:
Inefficiency: Bubble sort has a time complexity of O(n^2), making it inefficient for large datasets.
Poor Performance: It performs poorly compared to more efficient sorting algorithms like quicksort or mergesort, especially with large lists.
Overall, while bubble sort is simple and easy to implement, its inefficiency makes it less suitable for real-world applications where performance is critical.
Example:
The bubble sort algorithm can be implemented in C using nested loops for traversing the list and swapping adjacent elements as needed.
// Program for bubble sort in C #include<stdio.h>void bubbleSort(int arr[], int n) { int w1,w2, temp; for (w1 = 0; w1 < n-1; w1++) { for (w2 = 0; w2 < n-w1-1; w2++) { if (arr[w2] > arr[w2+1]) { temp = arr[w2]; arr[w2] = arr[w2+1]; arr[w2+1] = temp; } } } } int main() { int arr[] = {61, 33, 22, 12, 21, 13, 91}; int n = sizeof(arr)/sizeof(arr[0]); int e1; printf("Array before sorting: \n"); for (e1 = 0; e1 < n; e1++) printf("%d ", arr[e1]); printf("\n"); bubbleSort(arr, n); printf("Array after sorting: \n"); for (e1 = 0; e1 < n; e1++) printf("%d ", arr[e1]); printf("\n"); return 0; }
Output:
Array before sorting: 61 33 22 12 21 13 91 Array after sorting: 12 13 21 22 33 61 91
Share:
Comments
Waiting for your comments