Monday, March 23, 2020

BlueJ Program On 2 D Array and Sorting


Details of The Program: CLICK HERE

import java.io.*; 
public class P 
{ 
void sort(int arr[])          //Taking single dimension array as parameter 
{

int i, j, size = arr.length, temp,flag;

/*'size' holds the number of values in the array */ 
for(i=0;i 
{

flag=0; 
/*Sorting using bubble sort technique, so if there is no exchange of values in one pass there is no need to run the loop */ 
for(j=0;j 
{ 
if(arr[j]>arr[j+1])

{
flag=1; temp = arr[j]; 
arr[j] = arr[j+1]; 
arr[j+1] = temp; 
}

} 
if(flag==0)

break;
}

}

void show(int arr[][]) /*Taking 2D array as parameter*/ 
{

int i, j; for(i=0;i

{

for(j=0;j 
/* arr[i] gives one row at a time. arr[i].length gives the number of values in each row */ 
{ 
System.out.print(arr[i][j]+"\t"); 
}

System.out.println();

} 
}
 void sort2D(int arr[][]) 
{ 

/* In java, array is an object, so here the function calling technique is call be reference means any changes made to the formal parameter in this function will be reflected in the original parameter.*/


int i, j; 
for(i=0;i 
{ 
sort(arr[i]); 
} 
}
public static void main(String args[])throws Exception 
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

P obj = new P(); int arr[][], m, n, i, j; 
System.out.println("Enter the number of rows: "); 
m = 
Integer.parseInt(br.readLine()); 
System.out.println("Enter the number of columns: ");
n = Integer.parseInt(br.readLine()); 
if(m< 2 && m >9||n >9 && n< 2) 
{

System.out.println("Matrix out of range"); System.exit(0);

} 
arr = new int[m][n]; 
for(i=0;i
{
System.out.println("Enter values for row no "+(i+1) + ":"); for(j=0;j
{

System.out.print("\nColumn No " + (j+1) + ":"); arr[i][j] = Integer.parseInt(br.readLine()); 
} 
}
System.out.println("Original Matrix: ");
obj.show(arr); 
obj.sort2D(arr);

System.out.println("Matrix after sorting rows: "); obj.show(arr);
}
}

Variable Description

Type
Name
Use
BufferedReader
br
Intakes limit from user
int
arr
2 D array to hold the values
Int
m
Holds no of rows in the array
int
n
Holds no of columns in the


array

int
I,j
Loop Control Variable
int
size
Holds the no of elements in


each row the array
Algorithm




Step 1: Create BufferedReader object ‘br’ and int type variables ‘n’ and 'm' to store the column and row size of the 2 D array.

Step 2: Values of ‘n’ and 'm' are checked for validity and if it is invalid, terminate the program otherwise create the 2 D array 'arr'.

Step 3: Stores the values in the two dimensional array 'arr'.

Step 4: Display the original array


Step 5: Pass the two dimensional array to function 'sort2D()' which sends each rows of the 2 d array to 'sort()' function which sorts the elements bubble sort technique.


Back To 2018 Computer Practical Paper: CLICK HERE

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner