Java Program to Sort an Array in Ascending Order Using Bubble Sort

You are currently viewing Java Program to Sort an Array in Ascending Order Using Bubble Sort

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

// 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

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply