This article may contain affiliate links. If you buy some products using those links, I may receive monetary benefits. See affiliate disclosure here
In the previous post, I'd written the code that implement selection sort.
Here, we are going to take a look at Bubble sort. It's another algorithm that you can use to sort an array of values.
The algorithm repeatedly compares and swaps two consecutive elements to arrive at the final sorted array. Whereas in selection sort, each item is being compared with all the other elements repeatedly, not just the consecutive element.
So, at the end of the first iteration, the largest item goes to the far right in bubble sort. And in the next iteration, the comparison goes until the second last index, where the second largest item arrives, and so on until the smallest item comes at the first position (index zero).
Here is the program written in C:
Bubble Sort Program in C
#include <stdio.h>
void printArray(int numbers[], int n) {
int i;
for(i=0; i<n; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
}
void bubbleSort(int numbers[], int n) {
int i, j, temp;
for (i=0; i<n; i++) {
for (j=0; j<n-i-1; j++) {
if(numbers[j+1] < numbers[j]) {
temp = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = temp;
}
}
}
}
int main() {
int numbers[] = {325, 135, 25, 1025, 68, 17, 512, 468};
int length;
int n = sizeof(numbers) / sizeof(numbers[0]);
printf("Size of the array is %d\n", n);
printf("Here is the array before sorting:\n");
printArray(numbers, n);
bubbleSort(numbers, n);
printf("Here is the sorted array:\n");
printArray(numbers, n);
return 0;
}
in JavaScript
function printArray(numbers) {
console.log(numbers.join(" "));
}
function bubbleSort(numbers) {
let n = numbers.length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n - i - 1; j++) {
if (numbers[j + 1] < numbers[j]) {
let temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
}
let numbers = [325, 135, 25, 1025, 68, 17, 512, 468];
console.log("Size of the array is " + numbers.length);
console.log("Here is the array before sorting:");
printArray(numbers);
bubbleSort(numbers);
console.log("Here is the sorted array:");
printArray(numbers);
in PHP
<?php
function printArray($numbers) {
echo implode(" ", $numbers) . "\n";
}
function bubbleSort(&$numbers) {
$n = count($numbers);
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n - $i - 1; $j++) {
if ($numbers[$j + 1] < $numbers[$j]) {
$temp = $numbers[$j];
$numbers[$j] = $numbers[$j + 1];
$numbers[$j + 1] = $temp;
}
}
}
}
$numbers = [325, 135, 25, 1025, 68, 17, 512, 468];
echo "Size of the array is " . count($numbers) . "\n";
echo "Here is the array before sorting:\n";
printArray($numbers);
bubbleSort($numbers);
echo "Here is the sorted array:\n";
printArray($numbers);