0% found this document useful (0 votes)
16 views4 pages

Array Sorting Techniques in Java

The document discusses sorting of arrays and 2D arrays in Java. It provides 3 methods for sorting arrays: selection sort, bubble sort, and examples of each. It also discusses 2D arrays and provides 3 examples: 1) accepting and displaying values in a 2D array, 2) assigning values and displaying a matrix with left and right diagonal sums, and 3) calculating row and column sums of a given matrix.

Uploaded by

kidg830
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views4 pages

Array Sorting Techniques in Java

The document discusses sorting of arrays and 2D arrays in Java. It provides 3 methods for sorting arrays: selection sort, bubble sort, and examples of each. It also discusses 2D arrays and provides 3 examples: 1) accepting and displaying values in a 2D array, 2) assigning values and displaying a matrix with left and right diagonal sums, and 3) calculating row and column sums of a given matrix.

Uploaded by

kidg830
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Shri Vile Parle Kelavani Mandal's

[Link] & [Link] Pre-Primary School

Academic year 2023-2024


Std. X Subject: Computer Application

Worksheet – Array (Sorting )


The process of arranging data elements in the array which are randomly placed in either ascending
order or descending order is called sorting of the array.
Sorting of Array can be achieved through various ways. The two important sorting methods are:
1. Selection Sorting: The maximum or minimum element in array is determined and it is swapped
with first element, the same process is repeated for the second element, third element and so on. Such
method is called selection sorting.
import [Link].*;
class q3
{
public static void main( )
{ Scanner sc=new Scanner([Link]);
int a[] = new int [10];
[Link](" Enter 10 nos. for an array"); // accepting
for(int i=0;i<10;i++)
{ a[i]=[Link]( );
}
int small,tmp,pos;
for(int i=0;i<10;i++)
{
small=a[i];
pos=i;
for(int j=i+1;j<10;j++)
{
if(a[j]<small)
{ small=a[j];
pos=j;
}
}
tmp=a[i];
a[i]=a[pos];
a[pos]=tmp;
}
[Link]("Array in ascending order is --> ");
for(int i=0;i<10;i++)
[Link](a[i]);
} }
Bubble Sorting: - In bubble Sorting adjacent elements are compared. To arrange data elements in
ascending order, adjacent elements are compared, if the adjacent element is greater then they get inter
changed (swapping). It happens for the entire data. The process is repeated until all the data is sorted.

class Main
{
public static void main( )
{
int a[] = {64, 34, 25, 12, 22, 11, 90};
int len = [Link]; // calculating the length of array
for (int i = 0; i < len-1; i++)
{
for (int j = 0; j < len-i-1; j++)
{
if (a[j] > a[j+1]) // if(a[j].compareTo(a[j+1])>0)
{
int temp = a[j]; // String temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
for (int i = 0; i < len; i++)
{
[Link](a[i] + " "); //printing the sorted array
}
}
}
Define a class and store the given city names in a single dimensional array. Sort these names in
alphabetical order using the Bubble Sort technique only.
INPUT : Delhi, Bangalore, Agra, Mumbai, Calcutta
OUTPUT : Agra, Bangalore, Calcutta, Delhi, Mumbai

************************
2D Array
A two-dimensional array, also known as a 2D array, is a collection of data elements arranged in a grid-
like structure with rows and columns. Each element in the array is referred to as a cell and can be
accessed by its row and column indices/indexes.

int Array[][]= new int[R][C];

1. Accept and display integer values in 2D array.


import [Link];
public class Main
{
public static void main( )
{
Scanner scan = new Scanner([Link]);
[Link]("Enter number of rows: ");
int rows = [Link]();
[Link]("Enter number of columns: ");
int columns = [Link]();
int Array[][]= new int[rows][columns];

for (int i = 0; i < rows; i++) {


for (int j = 0; j < columns; j++)
{
[Link]("Enter number: ");
Array[i][j]= [Link]();
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
[Link](Array[i][j]+ " ");
}
[Link]();
}
}
}
******************************
2. Assign integer values in an 2D array and display matrix along with left and right diagonal
values.
public class MatrixDiagonals {
static public void main() {
int[][] input_matrix = {{ 4, 5, 6, 7 },{ 1, 7, 3, 4 },{ 5, 8, 4, 6 }, { 3, 2, 5, 1 }};
int matrix_size = 4;
[Link]("The matrix is defined as : ");
for (int i = 0; i < matrix_size; i++) {
for (int j = 0; j < matrix_size; j++)
[Link]( input_matrix[i][j] + " ");
[Link]("\n");
}
int left = 0, right = 0;
for (int i = 0; i < matrix_size; i++) {
for (int j = 0; j < matrix_size; j++) {
if (i == j)
left += input_matrix[i][j];
if ((i + j) == (matrix_size - 1))
right += input_matrix[i][j];
}
}
[Link]("\n The sum of Left diagonal elements of the matrix is: " + left);
[Link]("\n The sum of Right diagonal elements of the matrix is: " + right);
}
}}

3. Calculate the sum of elements in each row and each column of the given matrix.
public class SumofRowColumn
{
public static void main()
{
int rows, cols, sumRow, sumCol;

//Initialize matrix a
int a[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

//Calculates sum of each row of given matrix


for(int i = 0; i < 3; i++){
sumRow = 0;
for(int j = 0; j < 3; j++){
sumRow = sumRow + a[i][j];
}
[Link]("Sum of " + (i+1) +" row: " + sumRow);
}
//Calculates sum of each column of given matrix
for(int i = 0; i < 3; i++){
sumCol = 0;
for(int j = 0; j < 3; j++){
sumCol = sumCol + a[j][i];
}
[Link]("Sum of " + (i+1) +" column: " + sumCol);
}
}
}
*************************************

Common questions

Powered by AI

Using a 2D array to represent matrices in programming offers intuitive access to data through row and column indices, which aligns with mathematical representations . This structure allows straightforward implementation of matrix operations like addition, multiplication, and transformation. However, it lacks flexibility in resizing and can incur memory overhead due to fixed size allocation. Additionally, accessing elements might be inefficient in terms of cache use due to potential lack of data locality in certain access patterns, especially in large matrices .

In Java, a two-dimensional array is declared by defining the number of rows and columns. Integer elements are accepted from the user through a scanner, and these values are stored in the respective indices of the array through nested loops . The elements are then displayed using nested loops that print each element in row-major order, ensuring that each row is printed on a new line .

To calculate the sum of each row in a matrix, iterate through each row, keeping a running total of the elements in that row and printing the sum once the row has been traversed. The process is repeated for each row . Similarly, for the sum of each column, iterate through each column by fixing a column index and summing elements down that column, printing the sum at the end of each column iteration . This method efficiently computes sums using nested loops for row-wise and column-wise traversals.

Accept integer values for a 2D array by first obtaining from the user the number of rows and columns to define the array's size. Use nested loops to iterate over each element, during which a scanner accepts input for each position in the array . Display the array by iterating over each element with nested loops, printing each row's elements in sequence and moving to the next line after each row, effectively creating a matrix layout on the console .

To compute the sum of the left diagonal in a 2D matrix, add all elements where the row and column indices are equal. For the right diagonal, sum elements where the sum of the row and column indices equals one less than the size of the matrix . The significance of these computations lies in applications such as verifying matrix properties or solving problems related to symmetry and matrix transformations. In the example matrix provided, the sum of the left diagonal elements is calculated as the sum of matched row and column indices elements, and the right diagonal is calculated similarly but with indices whose sum equals matrix_size-1 .

To sort an array of city names alphabetically using the bubble sort method, compare adjacent city names and swap them if they are out of order. This process is repeated for all adjacent pairs across the list, and multiple passes are made through the list until no swaps are required, indicating the array is sorted alphabetically . Practical applications of bubble sort include educational purposes to illustrate sorting, as well as small datasets where simplicity is preferred over performance. It is also useful in situations where the data might already be nearly sorted, as bubble sort can quickly confirm this with early exits.

In a real-world scenario, bubble sort would be less effective when sorting large datasets, such as a database of millions of customer records. The inherent time complexity of O(n^2) makes it inefficient compared to other algorithms like quicksort or mergesort, which have average complexities of O(n log n). These more efficient algorithms better handle large volumes of data, minimizing the time and computational resources required for the sorting process. The only situation where bubble sort might be preferable is small data sets where simplicity and ease of implementation are more valued than raw performance.

Selection sort involves selecting the maximum or minimum element in the array and swapping it with the first unsorted element; this process is repeated for the remaining elements to sort the array in ascending or descending order . Bubble sort, on the other hand, involves repeatedly comparing adjacent elements and swapping them if they are in the wrong order, continuing this process for the entire array until it is sorted . Selection sort performs fewer swaps than bubble sort, but bubble sort can detect if the array is already sorted earlier in the process.

Common programming errors in matrix operations include index out of bounds errors when accessing elements or mismatching dimensions for operations such as addition or multiplication . These errors can be mitigated by performing thorough checks before operations, ensuring that dimensions align and indices remain within bounds. Additionally, using tried-and-tested libraries or frameworks for matrix operations can reduce the potential for errors. Automated testing frameworks can also be implemented to catch these issues by testing different edge cases and ensuring robustness in various scenarios.

Selection sort generally performs better than bubble sort in terms of number of swaps; it makes at most n-1 swaps in an array of n elements, whereas bubble sort can make up to n(n-1)/2 swaps in the worst case . In terms of time complexity, both have O(n^2) time complexity for average and worst cases, but selection sort is often faster for data types where swaps are relatively costly. Bubble sort’s advantage lies in its ability to recognize an already sorted list and terminate early, unlike selection sort which always performs the same number of comparisons .

You might also like