In this article you will find the following implementations:
- Suggested Reading: How Bubble Sort Work?
Bubble sort Using C:
// WAP to sort data using Bubble sort
#include <stdio.h>
void BubbleSort(int [], int);
void Display(int [], int);
int main()
{
int A[] = {55, 22, 44, 11, 33}, n = 5;
printf("Initially:--> ");
Display(A,n);
BubbleSort(A, n);
return 0;
}
void BubbleSort(int A[], int n)
{
int i, j, temp;
for(i = 0; i<n; i++)
{
for(j=0; j<n-i-1; j++)
{
if(A[j] > A[j+1])
{
// Swap elements if out of order
temp = A[j];
A[j] = A[j+1];
A[j+1] =temp;
}
}
// Display current array
printf("\nPass %d :--> ", i+1);
Display(A, n);
}
}
void Display(int A[], int n)
{
int i;
for(i=0; i<n; i++)
{
printf("%d ", A[i]);
}
}
Bubble sort Using C++:
// PROGRAM OF SORTING A ARRAY USING BUBBLE SORT
#include<bits/stdc++.h>
using namespace std;
void BubbleSort(int n,int A[]);
void Display(int n,int A[]);
int main()
{
int n = 5;
int A [] ={ 55,22,44,33,11};
BubbleSort(n,A);
return 0;
}
void BubbleSort(int n,int A[])
{
int temp;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n-i-1; j++)
{
if(A[j] > A[j+1])
{
temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
}
}
cout<<"PASS : "<< i+1 <<" ";
Display(n,A);
cout<<endl;
}
}
void Display(int n,int A[])
{
for(int i = 0; i < n; i++)
{
cout << A[i] <<" ";
}
}
Bubble Sort using Java:
import java.util.*;
public class BubbleSort
{
public void display(int a[] , int n)
{
for(int k = 0; k < n; k++)
{
System.out.print(a[k]+" ");
}
System.out.println("\n");
}
public void bubbleSort(int a[], int n)
{
int temp;
boolean swapped = false;
for(int i = 0; i < n; i++)
{
// Printing the passes
System.out.println("Pass"+i+"->");
display(a,n);
for(int j = 0; j < n-i-1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
swapped = true;
}
}
if(!swapped)
break;
}
}
public static void main(String[] args)
{
int n;
Scanner scan = new Scanner(System.in);
System.out.print("Enter size of array:");
n = scan.nextInt();
int[] a = new int[n];
System.out.println("enter the elements: \n");
for(int i = 0; i < n; i++)
{
a[i] = scan.nextInt();
}
BubbleSort obj = new BubbleSort();
obj.bubbleSort(a,n);
}
}
Bubble Sort using Python:
# WAP to sort data using Bubble sort
def BubbleSort(A, n):
# Traverse through all array elements
for i in range(n - 1):
# optimize code, so if the array is already sorted than no element will be swapped
flag = False
for j in range(0, n - i - 1):
# Swap if the element found is greater than the next element
if A[j] > A[j + 1]:
flag = True
A[j], A[j + 1] = A[j + 1], A[j]
if not flag: # if we haven't made a single swap, we can just say it is sorted.
return
print("Pass ", i + 1, " :-->", A)
# Main Function
A = [55, 33, 44, 11, 22]
n = len(A)
BubbleSort(A, n)