Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 6

Saturday, January 9, 2021

ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 6

 

Bubble Sort: JAVA Code

/*Question 5.

Write a program to input n integer elements in an array and sort them in ascending 
order using the bubble sort technique */

import java.util.*;
public class ICSEB6 {
       public static void main(String[] args) {
           int number_of_elements;
           Scanner input = new Scanner(System.in);
           System.out.println("Enter the number of elements in the array");
           number_of_elements = input.nextInt();
           bubbleSort obj = new bubbleSort(number_of_elements);
           obj.inputArrayElements();
           obj.bubbleSortMethod();
           obj.display();
           input.close();          
     }
}
class bubbleSort {
    public void display() {
        System.out.println("Array after bubble sort:");
        for(int i=0;i< number_of_elements;i++) 
            System.out.println(array[i]+ " ");
    }
    public void bubbleSortMethod() {
        for (int i = 0; i < number_of_elements-1; i++) 
            for (int j = 0; j < number_of_elements-i-1; j++) 
                if (array[j] > array[j+1]) 
                    { 
                    // swap array[j+1] and array[j] 
                    int temp = array[j]; 
                    array[j] = array[j+1]; 
                    array[j+1] = temp; 
                    }
    }
    public void inputArrayElements() {
        Scanner input = new Scanner(System.in);
        for(int i=0;i< number_of_elements;i++) {
            System.out.println("Enter the element at the position: "+(i+1));
            array[i] = input.nextInt();
        }
        input.close();
        System.out.println("Array before bubble sort:");
        for(int i=0;i< number_of_elements;i++) 
            System.out.println(array[i]+" ");
    }
    bubbleSort(int number_of_elements){
        this.number_of_elements = number_of_elements;
        array = new int[number_of_elements];
    }
    int []array;
    int number_of_elements;
}


No comments:

Post a Comment