Week 3-Multidimensional Array Concepts, Searching Sorting

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 44

Java Programming

CSCI431/CENG523

Prepared By
Ms.Fouzia Salma
SEARCHING & SORTING
LAB PROGRAM-WEEK-1
S.No Program
1 Write a program in Java which accept ten numbers in an array and display them from
first to last.
2 Write a program in Java which accept five numbers in an array and display them in
reverse order (last to first)

3 Write a program in java that prompts for an integer and then prints out all multiples of
7 numbers up to that number.
4 Write a program in java which store 10 numbers and find the sum of odd and even
numbers.
5 Write a program in Java which accept five numbers in an array and copy them into
another array in reverse order.
Searching Arrays

Searching is the process of looking for a specific element in


an array; for example, discovering whether a certain score
is included in a list of scores. Searching is a common task
in computer programming. There are many algorithms and
data structures devoted to searching. In this section, two
commonly used approaches are discussed, linear search
and binary search.
Linear Search in Java
• Step 1: Traverse the array.
• Step 2: Match the key element with array element.
• Step 3: If key element is found, return the index position of
the array element.
• Step 4: If key element is not found, return -1.
Linear Search
public class LinearSearchExample
{    
public static int linearSearch(int[] arr, int key)
{    
        for(int i=0;i<arr.length;i++)
{    
            if(arr[i] == key
{    
                return i;    
             }    
    }
     return -1;    
    } 
       
      
    public static void main(String a[])
{    
        int[] a1= {10,20,30,50,70,90};    
        int key = 50;    
        System.out.println(key+" is found at index: "+linearSearch(a1, 
key));    
    }    
}    

50 is found at index: 3
Binary search
• Binary search is used to search a key element from multiple
elements. Binary search is faster than linear search.
• In case of binary search, array elements must be in ascending
order. If you have unsorted array, you can sort the array
using Arrays.sort(arr) method.
class BinarySearch{    else
 public static void binarySearch(int arr[], int first, int last, int key) {  
{            last = mid - 1;  
   int mid = (first + last)/2;     }  
   while( first <= last )   mid = (first + last)/2;  
{      } 
      if ( arr[mid] < key )   if ( first > last )
{   {  
        first = mid + 1;            System.out.println("Element is not found!");  
      }    }   }  
else if ( arr[mid] == key ) public static void main(String args[])
{   {  
        System.out.println("Element is found at index: " + mid);           int arr[] = {10,20,30,40,50};  
        break;           int key = 30;  
      }         int last=arr.length-1;  
          binarySearch(arr,0,last,key);     
   }  }  
Sorting Arrays

Sorting, like searching, is also a common task in computer


programming
Many different algorithms have been developed for sorting.
This section introduces two simple, intuitive sorting algorithms:
selection sort and insertion sort.
What is Insertion Sort ?
• Insertion sort algorithm performs sorting by transferring one
element at a time to the partially sorted array.
• Consider the following example.
• 20  100  3  25  6  95  45  55
• We consider 20 is in the partially sorted array.
• Consider 100. It is greater than 100.  20 and 100 are in the partially
sorted array.
• Now, consider 3.  As it is less than 20, we can place it in the correct
position. Now 3, 20 and 100 are in the partially sorted array.
• 3  20   100  25  6  95  45  55
• Now, let’s consider 25. It is less than 100 but greater than 20, so
we can place it in the correct position. 3,20, 25,100 are now in the
partially sorted array.
• 3  20  25  100  6  95  45 55
• Let’s consider 6. It is greater than 3 but less than 20. So, we can
place it in the correct position. 3,6,20,25,100 are in the partially
sorted array.
• 3  6  20  25  100  95  45  55
• Let’s consider 95. It is greater than 25 but less than 100. We can
locate that element in the correct position.
• 3  6  20  25  95  100  45  55
• Now, consider 45. It is greater than 25 but less than 95. So, we can
place it in the correct position. 3, 6, 20, 25, 45, 95, 100 are in the
partially sorted array.
• 3  6  20  25  45  95  100  55
• Next, consider 55. It is greater than 45 but less than 95. Therefore,
we can place it in the correct position.
• 3  6  20  25  45  55  95  100
• Now, we can see that all the elements are sorted.
What is Selection Sort ?
• Selection sort performs sorting by selecting the smallest element
from the remaining elements and placing it at the correct position.
• Consider the following example.
• 20  100  3  25  6  95  45  55
• Here, the lowest element is 3. Therefore, we can exchange it with
the element in the first position (which is 20).
• 3  100   20  25  6  95  45  55
• The lowest element out of the remaining elements is 6. We can
exchange it with the element in the second position (which is 100).
• 3   6   20  25  100  95  45  55
• The smallest element out of the remaining elements is 20. It is
already in the 3rd position. Thus, there is no need for moving the
elements.
• Next, the smallest element out of the remaining is 25. It also is in
the 4th position, and there is no need for moving the elements.
• Now the minimum element out of the remaining is 45. We can
exchange it with the element in the 5th position (which is 100).
• 3  6  20  25  45  95 100  55
• The minimum element out of the remaining numbers is 55.
Therefore, we can exchange it with the element in the 6th position
which is 95.
• 3  6  20  25  45  55 100  95
• Now, the lowest element out of the remaining is 95. We can
exchange it with the element in the 7th position, which is 100.
• 3  6  20  25  45  55  95  100
• The remaining element is 100 and it is in the correct position. Now,
we can see that the elements are sorted.
TWO DIMENSIONAL ARRAY
Two-dimensional Arrays

// Declare array ref var


dataType[][] refVar;

// Create array and assign its reference to variable


refVar = new dataType[10][10];

// Combine declaration and creation in one statement


dataType[][] refVar = new dataType[10][10];

// Alternative syntax
dataType refVar[][] = new dataType[10][10];
Two-Dimensional Arrays
• A two-dimensional array is an array of arrays.
• It can be thought of as having rows and columns.

column 0 column 1 column 2 column 3

row 0

row 1

row 2

row 3
Two-Dimensional Arrays

• Declaring a two-dimensional array requires two sets of brackets and two size
declarators
• The first one is for the number of rows
• The second one is for the number of columns.
two dimensional array rows columns
double[][] scores = new double[3][4];

• The two sets of brackets in the data type indicate that the scores variable will
reference a two-dimensional array.
• Notice that each size declarator is enclosed in its own set of brackets.
Accessing Two-Dimensional Array
Elements
• When processing the data in a two-dimensional array, each element has
two subscripts:
• one for its row and
• another for its column.
Accessing Two-Dimensional Array
Elements
The scores variable
holds the address of a
2D array of doubles.
column 0 column 1 column 2 column 3
Address
row 0 scores[0][0] scores[0][1] scores[0][2] scores[0][3]

row 1 scores[1][0] scores[1][1] scores[1][2] scores[1][3]

scores[2][0] scores[2][1] scores[2][2] scores[2][3]


row 2
Accessing Two-Dimensional Array
Elements Accessing one of the elements in a two-dimensional
array requires the use of both subscripts.
The scores variable
holds the address of a
2D array of doubles.
column 0 column 1 column 2 column 3
Address
row 0 0 0 0 0
row 1 0 0 0 0
row 2 0 95 0 0
Accessing Two-Dimensional Array
Elements
• Programs that process two-dimensional arrays can do so with
nested loops.
• To fill the scores array:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
Scores[i][j] = scanner.nextInt();
}
System.out.println();
}
Accessing Two-Dimensional Array
Elements

• To print out the scores array:


for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 4; col++)
{
System.out.println(scores[row][col]);
}
}
Declaring Variables of Two-dimensional
Arrays and Creating Two-dimensional Arrays

int[][] matrix = new int[10][10];


or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;

for (int i = 0; i < matrix.length; i++)


for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)(Math.random() * 1000);

double[][] x;
Declaring, Creating, and Initializing Using
Shorthand Notations
You can also use an array initializer to declare, create
and initialize a two-dimensional array. For example,

int[][] array = { int[][] array = new int[4][3];


{1, 2, 3}, array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
{4, 5, 6}, Same as array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
{7, 8, 9}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
{10, 11, 12} array[3][0] = 10; array[3][1] = 11; array[3][2] =
}; 12;
Lengths of Two-dimensional Arrays

int[][] x = new int[3][4];


Lengths of Two-dimensional Arrays, cont.
int[][] array = { array.length
{1, 2, 3}, array[0].length
{4, 5, 6}, array[1].length
{7, 8, 9}, array[2].length
{10, 11, 12} array[3].length
};

array[4].length
ArrayIndexOutOfBoundsException
Declare Two Arrays
6000 27950 67700 141250 307050 Single filer
12000 46700 112850 171950 307050 Married jointly
6000 23350 56425 85975 153525 Married separately
10000 37450 96745 156600 307050 Head of household

10% int[][] brackets = {


{6000, 27950, 67700, 141250, 307050}, // Single filer
15%
{12000, 46700, 112850, 171950, 307050}, // Married
27% jointly
{6000, 23350, 56425, 85975, 153525}, // Married
30%
separately
35% {10000, 37450, 96700, 156600, 307050} // Head of
38.6% household
};
double[] rates = {0.10, 0.15, 0.27, 0.30, 0.35, 0.386};
Using Standard Method-Sample Program
class twodimestand
{
public static void main(String args[])
{    
int[][] a={{10,20},{30,40}};//declaration and initialization  
System.out.println("Two dimensional array elements are");    
System.out.println(a[0][0]);    
System.out.println(a[0][1]);    
System.out.println(a[1][0]);    
System.out.println(a[1][1]);    
}
}
Using For Loop
class twodimeloop
{
public static void main(String args[])
{    
int[][] a={{10,20},{30,40},{50,60}};//declaration and initialization  
System.out.println("Two dimensional array elements are");    
for (int i = 0; i < 3; i++)
{
            for (int j = 0; j < 2; j++)
    {
                System.out.println(a[i][j]);
            }
}}
}
class TwoDimensionalScanner
{
   public static void main(String args[])
   {    
Scanner sc=new Scanner(System.in);
System.out.println("Enter Row length of an array : ");
int row=sc.nextInt();
System.out.println("Enter column length of an array : ");
int column=sc.nextInt();
int a[][]=new int[row][column];//declaration    
System.out.print("Enter " + row*column + " Elements to Store in Array :\n");
       
 for (int i = 0; i < row; i++)
{
    for(int j = 0; j < column; j++)
    {
           a[i][j] = sc.nextInt();
    }
}  
        System.out.print("Elements in Array are :\n");
        for (int i = 0; i < row; i++)
{
    for(int j = 0; j < column; j++)
    {
       System.out.println("Row ["+i+"]:  Column ["+j+"] :"+a[i][j]);
    }
}  }
}
Multidimensional Arrays

Occasionally, you will need to represent n-


dimensional data structures. In Java, you can create
n-dimensional arrays for any integer n.
The way to declare two-dimensional array variables
and create two-dimensional arrays can be
generalized to declare n-dimensional array variables
and create n-dimensional arrays for n >= 3. For
example, the following syntax declares a three-
dimensional array variable scores, creates an array,
and assigns its reference to scores.

 double[][][] scores = new double[10][5][2];


Array of Objects
Elements of an array can be objects of any Java class.

Example: An array of 5 instances of the student class

Student[ ] topStudents = new Student[5];


public class marks
{
String name;
double mark;
static Scanner sc=new Scanner(System.in);
public static void main(String[] args)
{
marks[] m=new marks[2];
for(int i=0;i<2;i++)
{
m[i]=new marks();
System.out.println("Enter Student name and marks");
m[i].name=sc.next();
m[i].mark=sc.nextDouble();
}
SEAT WORK :
Create a class salary, to calculate the salary of 7 employees. For
each employee we have to store his da, ta, basic. Find the total
salary for each employee and print it neatly with all the details.
LAB PROGRAM-WEEK-2
S.No Program
1 Write a program to search an element in a given array using linear search.
2 Create a program that uses a two dimensional array that can store integer values inside. (Just create an
array with your own defined rows and columns). Make a method called Square, which gets each of the
value inside the array and squares it. Make another method called ShowNumbers which shows the squared
numbers.
3 Design, Develop and Implement a menu driven Program in Java for the following String operations.

a) Read a two Strings (STR1 & STR2),


b) Find length of strings.
c) Copy second string into first string.
d) Compare the two strings, display suitable messages for string comparison.
e) Convert each characters of strings into opposite case and display.
f) Reverse and display the given strings.
g) Find the substring of the given string.
h) Exit
Support the program with methods for each of the above operations.

You might also like