Bubble Sort in Java
Q. Write a Java program for Bubble Sort
import java.util.Scanner;
public class BubbleSort {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input array size
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
// Read array elements
System.out.println("Enter " + n + " integers:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
// Bubble Sort algorithm
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Display sorted array
System.out.println("Sorted array in ascending order:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
scanner.close();
}
}
Q. Write an algorithm for Bubble Sort
1. Start
2. Read n (number of elements)
3. Read n elements into array arr[]
4. Repeat for i = 0 to n - 2:
a. Repeat for j = 0 to n - 2 - i:
If arr[j] > arr[j + 1], swap arr[j] and arr[j + 1]
5. Print the sorted array
6. End
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com