Bubble Sort(Ascending) in Java

Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items, and swaps them if they are in the wrong order. This process is repeated until the entire list is sorted ascending order, with the smallest element at the beginning and the largest element at the end.

JAVA PROGRAMMING

Raki Adhikary

1/12/20231 min read

import java.util.*;

public class BubbleSort {

public static void main(String args[]) {

int size;

Scanner scanner = new Scanner(System.in);

System.out.println("Enter the size of the array:");

size = scanner.nextInt();

int array[] = new int[size];

int i, j, temp;

/* Taking input in the array */

for (i = 0; i < size; i++) {

System.out.println("Enter element at index " + i + ":");

array[i] = scanner.nextInt();

}

/* Bubble Sorting the array */

for (i = 0; i < size - 1; i++) {

for (j = 0; j < size - 1 - i; j++) {

if (array[j] > array[j + 1]) {

// Swapping if the current element is greater than the next one

temp = array[j];

array[j] = array[j + 1];

array[j + 1] = temp;

}

}

}

/* Displaying the sorted Array */

System.out.println("The sorted Array is:");

for (i = 0; i < size; i++)

System.out.print(array[i] + " ");

scanner.close();

}

}

Your Code is here