Java program to bubble sort
Example:
import java.util.Scanner;
class BubbleSorting {
public static void main(String []args) {
int inputsLength, swap;
Scanner in = new Scanner(System.in);
System.out.println("Input number of integers to sort: ");
inputsLength = in.nextInt();
int array[] = new int[inputsLength];
System.out.println("Enter " + inputsLength + " integers");
for (int i = 0; i < inputsLength; i++)
{
array[i] = in.nextInt();
}
for (int i = 0; i < ( inputsLength - 1 ); i++) {
for (int d = 0; d < inputsLength - i - 1; d++) {
if (array[d] > array[d+1])
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
System.out.println("Sorted list of numbers");
for (int i = 0; i < inputsLength; i++)
{
System.out.println(array[i]);
}
}
}
Output:
Input number of integers to sort: 3 Enter 3 integers Sorted list of numbers 5 10 20
Complexity of bubble sort is O(n2)
Share this page on:
Subscribe Email Updates
to get latest update