Java program to sort an array in ascending order using bubble sort

Given/input an array, we have to sort an array in ascending order using bubble sort.
By Nidhi Last updated : December 23, 2023

In the bubble sort sorting technique, we compare adjacent elements and swap if they are in the wrong order. This process repeats until no more swaps are needed.

Problem statement

In this program, we will create an array of integers then we will sort array elements in ascending order using bubble sort.

Java program to sort an array in ascending order using bubble sort

The source code to sort an array in ascending order using bubble sort is given below. The given program is compiled and executed successfully.

// Java program to sort an array in ascending order 
// using bubble sort

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    int i = 0;
    int j = 0;
    int t = 0;

    int arr[] = {
      14, 49, 79, 87, 78};

    //Sort array using bubble sort.
    while (i < 5) {
      j = 4;
      while (j > i) {
        if (arr[j] < arr[j - 1]) {
          t = arr[j];
          arr[j] = arr[j - 1];
          arr[j - 1] = t;
        }
        j = j - 1;
      }
      i = i + 1;
    }

    System.out.println("Sorted Array in ascending order: ");
    i = 0;
    while (i < 5) {
      System.out.print(arr[i] + " ");
      i = i + 1;
    }
  }
}

Output

Sorted Array in ascending order: 
14 49 78 79 87

Explanation

In the above program, we imported the java.util.Scanner package to read the variable's value from the user. And, created a public class Main. It contains a static method main().

The main() method is an entry point for the program. Here, we created an array. Then we sorted the array elements in ascending order using the bubble sort technique and printed the updated array.

Java Array Programs »

More Java Array Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.