Tuesday, April 16, 2013

How to sort numbers in Bubble Sort : JAVA OOP

Write a Java Source Code: How to sort numbers in Bubble Sort

Sample Output:
Enter the size of the array: 10
Enter 10 numbers: 100 35 45 3 7 2 1 500 200 15
The Sorted Numbers: 1 2 3 7 15 35 45 100 200 500

Java Source Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//java class
public class BubbleSort
{
 public void bubbleSort(int[] arr){
     for(int i=0; i<arr.length; i++){
        for(int j=1; j<arr.length; j++){
            if(arr[j]< arr[j-1] ){
                int temp = arr[j];
                arr[j] = arr[j-1];
                arr[j-1] = temp;           
            }
        }
     }
     for(int i=0; i<arr.length; i++)
     {
         System.out.print(arr[i] + " ");
     }
}
}
//main class
import java.util.Scanner;
public class Main
{
    
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the size of the array: ");
        int n = input.nextInt();
        int[] x = new int[n];
        System.out.print("Enter "+ n +" numbers: ");
        for(int i=0; i<n; i++)
        {
            x[i] = input.nextInt();
        }
         
        BubbleSort access = new  BubbleSort();
    System.out.print("The Sorted numbers: ");
        access.bubbleSort(x);
    }
}

1 comment:

  1. Mohammad Ashraful Hasan Sobuj
    My Batch- 46th
    My Department :CSE
    My ID 201420656



    public class BubbleSort
    {
    public void bubbleSort(int[] a)
    {
    for(int i=0; i<arr.length; i++)
    {
    for(int j=1; j<arr.length; j++)
    {
    if(a[j]< a[j-1] )
    {
    int temp = a[j];
    a[j] = a[j-1];
    a[j-1] = temp;
    }
    }
    }
    for(int i=0; i<a.length; i++)
    {
    System.out.print(a[i] + " ");
    }

    import java.util.Scanner;
    public class Main
    {

    public static void main(String[] args)
    {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the size of the array: ");
    int n = input.nextInt();
    int[] x = new int[n];
    System.out.print("Enter "+ n +" numbers: ");
    for(int i=0; i<n; i++)
    {
    x[i] = input.nextInt();
    }

    BubbleSort access = new BubbleSort();
    System.out.print("The Sorted numbers: ");
    access.bubbleSort(x);
    }
    }

    ReplyDelete