

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
questions based on bubble sort of java
Typology: Assignments
1 / 3
This page cannot be seen from the preview
Don't miss anything!


Question 1 A class myArray contains an array of n integers (n<=100). The subscripts of the array elements vary from 0 to n- 1. Some of the members of the class myArray are given below: Class name : myArray Data members/instance variables : arr[ ] : integer array to store elements. n : size of the array. Member functions/methods : myArray( int size ) : parameterized constructor to assign n=size and create the array. void readArray( ) : to read n integers into the array arr[ ]. void BubSort( ) : sorts the array in descending order using Bubble sort method. void displayArray( ) : displays n integers. Specify the class myArray giving details of the constructors and functions void readArray( ) , void BubSort( ) and void displayArray( ). Write a main( ) function to create an object and call the functions accordingly to input the array, print the array before and after sorting. Solution: import java.util.;* class myArray { int arr[ ]; //array declaration int n; //parameterized constructor myArray( int size ) { n = size; arr = new int[ n ]; //creating array }//end constructor void readArray( ) //function to input the array { Scanner sc = new Scanner( System. in ); for( int i = 0; i < n ; i++ ) { System.out.print("Input a number for array = " ); arr[ i ] = sc. nextInt( ); }//end loop }//end function
void BubSort( ) //bubble sorting is done here { for( int i = 0; i < n - 1 ; i++ ) {
if( arr[ j ] > arr[ j + 1 ]) //check adjacent element { // swapping or interchanging numbers int t = arr[ j ]; arr[ j ] = arr[ j + 1 ]; arr[ j + 1 ] = t; }//end if }//end for j loop }//end for i loop }//end function void displayArray( ) { System.out.println("The elements of array:" ); for( int i = 0; i < n; i++ ) { System.out.println( arr[ i ] ); //printing array elements }//end loop }//end function //making main method public static void main( String args[ ] ) { Scanner sc = new Scanner( System. in ); System.out.print("Enter the size of the array <= 100 : = " ); int N = sc. nextInt( ); // making below the object of the class myArray obj = new myArray( N ); //this 'N' goes to parameterized constructor //and variable 'size' receives it