Bubble sort With code in JAVA/C++/C/Go
What is Bubble sort?
Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. This sorting algorithm gets its name because smaller elements "bubble" to the top of the list with each pass.
Here is an algorithm of bubble sort-
- Start at the beginning of the list.
- Compare the first two elements. If the first is greater than the second, swap them.
- Move to the next pair of elements, and so on, continuously making comparisons and swapping if necessary.
- After the first pass, the largest element will be in its correct position at the end of the list.
- Repeat this process for the remaining elements, each time starting one element earlier.
- Continue until no swaps are needed, indicating that the list is sorted.
Implementation of Bubble sort-
static void bubbleSort(int[] array) { int n = array.length; for (int i = 0; i < n-1; i++) { for (int j = 0; j < n-i-1; j++) { if (array[j] > array[j+1]) { // swap array[j] and array[j+1] int temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; } } } }
void bubbleSort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { 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; } } } }
void bubbleSort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { 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; } } } }
func bubbleSort(arr []int) { n := len(arr) for i := 0; i < n-1; i++ { for j := 0; j < n-i-1; j++ { if arr[j] > arr[j+1] { // Swap arr[j] and arr[j+1] arr[j], arr[j+1] = arr[j+1], arr[j] } } } }
Bubble sort complexity-
Time Complexity | ||
---|---|---|
Best case | Average case | Worst case |
O(n) | O(n2) | O(n2) |
Space Complexity |
---|
O(1) |
Thank you for your valuable time!
Join the conversation