Description
* Bubble sort repeatedly swap the adjacent elements if they are not sorted.
* Largest element repeatedly move to highest index, if elements are sored
in acscending order or smallest element move to highest index if it
sorted in descending order.
* Time Complexity: O(n2) : Worst and Average Case.
: O(n) : Best Case (when array is already sorted).
C/C++
/* C program of Bubble sort */
//Save it as BubbleSort.c
#include<stdio.h>
int main()
{
int i,n;
printf("Enter the size of array : ");
scanf("%d",&n);
int arr[n];
printf("\nEnter element : ");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
bubbleSort(arr,n);
printf("\nThe Sorted array is : ");
for(i=0;i<n;i++)
{
printf("%d ",arr[i]);
}
return 0;
}
void bubbleSort(int arr[], int n){
int i, j;
for(i=0;i<n-1;i++){
for(j=(i+1);j<n;j++){
if(arr[i] > arr[j]){
swap(&arr[i], &arr[j]);
}
}
}
}
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
Input: Enter the size of array : 6 Enter element : 45 25 6 46 37 56 Output: The Sorted array is : 6 25 37 45 46 56
Java
/* Java program of Bubble sort */
//Save it as BubbleSort.java
import java.io.*;
import java.util.Scanner;
public class BubbleSort {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i,n;
System.out.println("Enter the size of array : ");
n = scanner.nextInt();
int arr[] = new int[n];
System.out.println("Enter element : ");
for(i=0;i<n;i++)
{
arr[i] = scanner.nextInt();
}
bubbleSort(arr,n);
System.out.println("\nThe Sorted array is : ");
for(i=0;i<n;i++)
{
System.out.print(arr[i]+ " ");
}
}
private static void bubbleSort(int[] arr, int n) {
int i, j;
for(i=0;i<n-1;i++) {
for(j=(i+1);j<n;j++) {
if(arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
Input: Enter the size of array : 5 Enter element : 26 34 15 65 43 Output: The Sorted array is : 15 26 34 43 65
Related Programs
1) Selection Sort2) Insertion Sort
3) Program of Merge Sort
4) Quick Sort