top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Write a Java program to sort a array using Bubble Sort algorithm?

+3 votes
434 views
Write a Java program to sort a array using Bubble Sort algorithm?
posted Aug 11, 2015 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer
import java.util.Scanner;

class BubbleSort {
  public static void main(String []args) {
    int n, c, d, swap;
    Scanner in = new Scanner(System.in);

    System.out.println("Input number of integers to sort");
    n = in.nextInt();

    int array[] = new int[n];

    System.out.println("Enter " + n + " integers");

    for (c = 0; c < n; c++) 
      array[c] = in.nextInt();

    for (c = 0; c < ( n - 1 ); c++) {
      for (d = 0; d < n - c - 1; d++) {
        if (array[d] > array[d+1]) /* For descending order use < */
        {
          swap       = array[d];
          array[d]   = array[d+1];
          array[d+1] = swap;
        }
      }
    }

    System.out.println("Sorted list of numbers");

    for (c = 0; c < n; c++) 
      System.out.println(array[c]);
  }
}

Complexity of bubble sort is O(n2) which makes it a less frequent option for arranging in sorted order when quantity of numbers is high.

answer Aug 14, 2015 by Karthick.c
Similar Questions
+1 vote

Write a program to print the sum of the elements of the array with the given below condition. If the array has 6 and 7 in succeeding orders, ignore 6 and 7 and the numbers between them for the calculation of sum.
Eg1) Array Elements - 10,3,6,1,2,7,9
O/P: 22
[i.e 10+3+9]
Eg2) Array Elements - 7,1,2,3,6
O/P:19
Eg3) Array Elements - 1,6,4,7,9
O/P:10

0 votes

Write a program to reverse the elements of a given 2*2 array. Four integer numbers needs to be passed as Command Line arguments.

Example1:

 C:\>java Sample 1 2 3

 O/P Expected : Please enter 4 integer numbers

Example2:

 C:\>java Sample 1 2 3 4

 O/P Expected : 

The given array is :
1 2
3 4
The reverse of the array is :
4 3
2 1

1 2 3 4
5 6 7 8
9 10 11 12

...