0% found this document useful (0 votes)
10 views

Arrays

Arrays allow storing multiple values of the same type. They can be single, two, or three dimensional. Single dimensional arrays store elements in a single list. Two dimensional arrays create an array of arrays, with two indices. Three dimensional arrays create an array of two dimensional arrays, with three indices to access elements.

Uploaded by

Sanjad Khan
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)
10 views

Arrays

Arrays allow storing multiple values of the same type. They can be single, two, or three dimensional. Single dimensional arrays store elements in a single list. Two dimensional arrays create an array of arrays, with two indices. Three dimensional arrays create an array of two dimensional arrays, with three indices to access elements.

Uploaded by

Sanjad Khan
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
You are on page 1/ 14

Arrays

Topics we are going to cover


1. Introduction
2. Arrays Declaration
3. Arrays Construction

1. Introduction:
An Array is an index collection of homogeneous elements.
Homogeneous elements is nothing similar type elements.
Advantages:
1. The main advantage of arrays is we can store multiple values of
Same type.
Dis-Advantage:
1. Arrays are fixed in size, once we declare an array we cannot
increase or decrease the size of an array.
2. To use arrays we should know the size in advance, which is not
possible every time.
How to resolve this problem?
We can resolve this problem using collections, we will be learning
collections in our future lectures.
What are the different types of array, how we can declare an Arrays?
In Arrays we have multiple dimensions, they are as.
1. Single dimension array
2. Two dimensional array
3. Three dimensional array

1. Single Dimension Array:


A single dimension array one which will be having one array
defined after the datatype as shown below.

Here, the datatype is the type of element that will be stored in the
array, square bracket[] is for the size of the array, and variableName is the
name of the array.

Initializing an Array:
1. Without new operator
2. With new operator

1. Without new operator:

Here
1. datatype represent type of data we are going to store.
2. VariableName represents, what is the variable-name we are going to give to
our array.
3. {value1,value2,value3,value4....value-n} represent the values we are going
to store.
Example:

1. With new operator:


• We will be creating an array using new keyword/operator.
• While creating an array compulsory we should specify the size,
otherwise we will get compiler time error.
Syntax of creating an Array using new operator

1. Datatype represents what type of data we are using to store


elements/objects/values.
Example: int, float, char, double etc...
2. VariableName represents name of the object.
3. Specify_size_of_array is nothing but we will be specifying
certain size/number for creating an array.
Example:
int[3]; // this represent an Array with Size 3
int[4]; // this represent an Array with Size 4
int[5]; // this represent an Array with Size 5
float[10]; // this represent an Array with Size 10
char[6]; // this represent an Array with Size 6
double[12]; // this represent an Array with Size 12

Creating an Array using new operator isn’t enough we should add some
elements to it, to add elements we have syntax.
Syntax for adding elements/values to an Array index:
VariableName[i] =value;
here ‘i’ represents index position
example: 0,1,2,3,4...n
example for adding elements to an Array index:
numbers[0]=10;
numbers[1]=20;
numbers[2]=30;
numbers[3]=40;
syntax for retrieving/getting the values from Arrays specific index
variableName[i];
here ‘i’ represents index position
example: 0,1,2,3,4...n
numbers[0];
numbers[1];
numbers[2];
numbers[3];
How to add and retrieve the elements or values to/from an Array:
Example program:

Note: we can create an array with Zero size.

What happened if you/we specify –ve size?


We will be getting runtime errors, as negative size wont considered
We will be getting NegativeArraySizeException.
Example:

Multi-dimensional Arrays
In java multi-dimensional arrays are nothing but arrays of arrays.
Advantages:
The main advantage is it improves the memory utilization.
Multi-dimensional arrays can be any, but in this course we will discussing only
two, they are as follows.
1. Two dimensional Arrays
2. Three Dimensional Arrays
1. Two dimensional Array:
A Two dimension array one which will be having two Square brackets
defined after the datatype.

Here,
1. the datatype represents the type of value we are going to store in the
array, in square bracket[][]’s we will be defining the size of the array.
2. variableName is the objectName of the array.
3. Datatype[size][size] will be taking the size for the multi-dimensional
arrays.
Note:
You shouldn’t declare the size of the array at left hand side, as
shown below.
Example:

example:
int[2][]; //valid
Int[2][2]; // valid
Example for declaring two-dimensional array:
int [][] numbers=new int[2][];
numbers[0]=new int[3];
numbers[1]=new int[2];

Let’s have a look how memory representation will happen.

Example program:
package com.core.java.examples;

public class TwoDimesionalArrayExample {

public static void main(String nits[]) {


int[][] naturalNumbers = new int[2][];
naturalNumbers[0] = new int[3];
naturalNumbers[1] = new int[2];

// assigning values
naturalNumbers[0][0] = 10;
naturalNumbers[0][1] = 20;
naturalNumbers[0][2] = 30;

// assigning values for index naturalNumbers[1]


naturalNumbers[1][0] = 40;
naturalNumbers[1][1] = 50;

System.out.println("Number at naturalNumbers[0] is:" + naturalNumbers[0]);


System.out.println("============================================");
System.out.println("Number at naturalNumbers[0][0] is:" + naturalNumbers[0][0]);
System.out.println("Number at naturalNumbers[0][1] is:" + naturalNumbers[0][1]);
System.out.println("Number at naturalNumbers[0][2] is:" + naturalNumbers[0][2]);
System.out.println("....................>>>>>>>>>>>............................");
System.out.println("Number at naturalNumbers[1] is:" + naturalNumbers[1]);
System.out.println("-------------------------------------------------------------");
System.out.println("Number at naturalNumbers[0][1] is:" + naturalNumbers[1][0]);
System.out.println("Number at naturalNumbers[0][2] is:" + naturalNumbers[1][1]);

}
}
Output:
Number at naturalNumbers[0] is:[I@15db9742
============================================
Number at naturalNumbers[0][0] is:10
Number at naturalNumbers[0][1] is:20
Number at naturalNumbers[0][2] is:30
....................>>>>>>>>>>>............................
Number at naturalNumbers[1] is:[I@6d06d69c
-------------------------------------------------------------
Number at naturalNumbers[0][1] is:40
Number at naturalNumbers[0][2] is:50

2. Three Dimensional Array:


A three-dimension array is one which will be having three Square
brackets defined after the datatype.

syntax for creating three-dimesional arrys


---------------------------------------------------
datatype[][][] varibleName/objectName=new int[size][size][size];

Example for declaring three-dimensional array


-------------------------------------------

int[][][] values=new int[2][][];


values[0]=new int[3][];
values[0][0]=new int[1];
values[0][1]=new int[2];
values[0][2]=new int[3];
values[1]=new int[2][];
values[1][0]=new int[2][];
values[1][1]=new int[1][];

Example:
package com.core.java.examples;

public class ThreeDimesionalArrayExample {

public static void main(String nits[]) {


int[][][] naturalNumbers = new int[2][][];
naturalNumbers[0] = new int[3][];
naturalNumbers[1] = new int[2][];

// creating two-dimensional object inside 3D


naturalNumbers[0][0] = new int[2];
naturalNumbers[0][1] = new int[3];
naturalNumbers[0][2] = new int[1];

// creating one-dimensional object inside 3D


naturalNumbers[1][0] = new int[2];
naturalNumbers[1][1] = new int[1];

// now assigning values to index-naturalNumbers[0][0]


naturalNumbers[0][0][0] = 40;
naturalNumbers[0][0][1] = 50;

// now assigning values to index-naturalNumbers[0][1]


naturalNumbers[0][1][0] = 60;
naturalNumbers[0][1][1] = 70;
naturalNumbers[0][1][2] = 80;
// now assigning values to index-naturalNumbers[0][2]
naturalNumbers[0][2][0] = 90;

// now assigning values to index-naturalNumbers[1][0]


naturalNumbers[1][0][0] = 100;
naturalNumbers[1][0][1] = 110;
// now assigning values to index-naturalNumbers[1][1]
naturalNumbers[1][1][0] = 120;

System.out.println("Number at naturalNumbers[0][0][0] is:" + naturalNumbers[0][0]);


System.out.println("============================================");
System.out.println("Number at naturalNumbers[0][0][0] is:" + naturalNumbers[0][0][0]);
System.out.println("Number at naturalNumbers[0][0][1] is:" + naturalNumbers[0][0][1]);
System.out.println("============================================");
System.out.println("Number at naturalNumbers[0][1][0] is:" + naturalNumbers[0][1][0]);
System.out.println("Number at naturalNumbers[0][1][1] is:" + naturalNumbers[0][1][1]);
System.out.println("Number at naturalNumbers[0][1][2] is:" + naturalNumbers[0][1][2]);

System.out.println("....................>>>>>>>>>>>............................");
System.out.println("Number at naturalNumbers[0][2] is:" + naturalNumbers[0][2]);
System.out.println("-------------------------------------------------------------");
System.out.println("Number at naturalNumbers[0][2][0] is:" + naturalNumbers[0][2][0]);
System.out.println("/////////////////////<<<<<<<<<<<>>>>>>>>>>>>>/////////////////////");
System.out.println("Number at naturalNumbers[0][2] is:" + naturalNumbers[1][0]);

System.out.println("Number at naturalNumbers[0][1][0] is:" + naturalNumbers[1][0][0]);


System.out.println("Number at naturalNumbers[0][1][1] is:" + naturalNumbers[1][0][1]);
System.out.println("-------------------------------------------------------------------");
System.out.println("Number at naturalNumbers[1][1] is:"+naturalNumbers[1][1]);
System.out.println("Number at naturalNumbers[0][1][2] is:" + naturalNumbers[1][1][0]);

}
}
Output:
Number at naturalNumbers[0][0] is:[I@15db9742
============================================
Number at naturalNumbers[0][0][0] is:40
Number at naturalNumbers[0][0][1] is:50
============================================
Number at naturalNumbers[0][1][0] is:60
Number at naturalNumbers[0][1][1] is:70
Number at naturalNumbers[0][1][2] is:80
....................>>>>>>>>>>>............................
Number at naturalNumbers[0][2] is:[I@6d06d69c
-------------------------------------------------------------
Number at naturalNumbers[0][2][0] is:90
/////////////////////<<<<<<<<<<<>>>>>>>>>>>>>/////////////////////
Number at naturalNumbers[0][2] is:[I@7852e922
Number at naturalNumbers[0][1][0] is:100
Number at naturalNumbers[0][1][1] is:110
-------------------------------------------------------------------
Number at naturalNumbers[1][1] is:[I@4e25154f
Number at naturalNumbers[0][1][2] is:120
Programs to practice
1. write a java program to store the 10,20,30,40,50,60 values in a 3-dimensional
array and display the values stored in array?
2. write a java program to store the 102,200,300,400,500,600 values in a 3-
dimensional array and display the values stored in array?
3. write a java program to store the 1000,2000,3000,4000,5000,6000 values in a
3-dimensional array and display the values stored in array?
1. write a java program to store the 1.2f,2.3f,3.2f,4.5f,5.2f,6.3f values in a
3-dimensional array and display the values stored in array?
5. write a java program to store the 10.5f,20.1f,30.3f,40.5f,50.2f,60.5f values in
a two-dimensional array and display the values stored in array?
6. write a java program to store the 100.2f,200.3f,300.4f,400.500.600.7f values in
a 3-dimensional array and display the values stored in array?
7. write a java program to store the vowles 'a','e','i','o,'u' values in a
3-dimensional array and display the values stored in array?
8. write a java program to store the consonants 'F','L','M','N','Q','R' values in a
3-dimensional array and display the values stored in array?
9. write a java program to store the consonants 'S','V','W','X','Y', values in a
3-dimensional array and display the values stored in array?
10. write a java program to store the vowles "Hello","Java","Developer" values in a
3-dimensional array and display the values stored in array?
11. write a java program to store the months
"JAN","FEB",",MAR","APR","MAY","JUNE","JULY","AUG"
"SEP","OCT","NOV","DEC" values in a 3-dimensional array and display the values
stored in array?
12. write a java program to store the days
"SUN","MON",","TUE","WED","THU","FRI","SAT" values in a 3-dimensional array and
display the values stored in array?
Methods Available in Arrays
Length variable:

a. Length is final variable


b. It is used to identify size of the array.
1. Public int length()
2. public static datatype[] copyOf(datatype[] array, int newLength)
3. public static datatype[] copyOfRange(datatype[] array, begIndex, endIndex)
4. public static void sort(datatype[] array)
5. public static void sort(datatype[] array, fromIndex, toIndex)
6. public static List asList(datatype[] array)
7. public static int binarySearch(datatype[] a, datatype key)
8. public static int binarySearch(datatype[] a, fromIndex, toIndex, key)
9. public static void parallelSort(datatype[] array)
10. public static void parallelSort(datatype[] array, fromIndex, toIndex)

1. length()
a. length method is final
b. It is used to identify the size of given string or string[].
c. This method will be applicable only on String

2. copyOf(datatype[] array, int newLength)


This method is used to create a new Array from an existing array.
Syntax of this method:

public static datatype[] copyOf(datatype[] existing-array, LengthOfArrayYouWantToCreate)

1) This is the syntax for copyOf() method.


2) This method receives an existing array and length, here length is nothing but, length of a
new array, which we want to create.

3) This method returns a new array with the values from an old array.
4) Here datatype represents, type of data your’e storing in an existing-array.
You can take any data type
int, long, float, double, char, short, byte, boolean.

LengthOfArrayYouWantToCreate is nothing but length of the new array you want to create from an existing-array.
for example:
int[] existingArray = { 10, 20, 30, 40, 50, 60 };

int[] newArray = Arrays.copyOf(existingArray, 4);

for (int j = 0; j < newArray.length; j++) {

System.out.println (newArray[j]);

Methods you can create from syntax of copyOf() Method


---------------------------------------------------

o public static int[] copyOf(int[] existing-array, int LengthOfArrayYouWantToCreate)


o public static long[] copyOf(long[] existing-array, int LengthOfArrayYouWantToCreate)
o public static float[] copyOf(int[] existing-array, float LengthOfArrayYouWantToCreate)
o public static double[] copyOf(double[] existing-array, double
LengthOfArrayYouWantToCreate)
o public static char[] copyOf(char[] existing-array, int LengthOfArrayYouWantToCreate)
o public static short[] copyOf(short[] existing-array, int LengthOfArrayYouWantToCreate)
o public static byte[] copyOf(byte[] existing-array, int LengthOfArrayYouWantToCreate)
o public static boolean[] copyOf(boolean[] existing-array, int
LengthOfArrayYouWantToCreate)

copyOfRange()

Definition 1: if we want to copy array values from the given Range (beginIndex and
endIndex), then we have to use copyOfRange() method.

Syntax:

public return[] copyOfRange(datatype[] original, fromIndex, toIndex)

List of overloaded methods with range (begIndex, endIndex)

---------------------------------------------------------

o public int[] copyOfRange(int[] original, fromIndex, toIndex)


o public float[] copyOfRange(float[] original, fromIndex, toIndex)
o public char[] copyOfRange(char[] original, fromIndex, toIndex)
o public double[] copyOfRange(double[] original, fromIndex, toIndex)
o public byte[] copyOfRange(byte[] original, fromIndex, toIndex)
o public short[] copyOfRange(short[] original, fromIndex, toIndex)
o public boolean[] copyOfRange(boolean[] original, fromIndex, toIndex)

example:

package com.core.java.examples;

import java.util.Arrays;

public class CopyOfMethodExample {

public static void main(String[] args) {

int a1[] = { 10, 20, 30, 40 };


int[] resultantArray = Arrays.copyOfRange(a1, 0, 2);
for (int i = 0; i < resultantArray.length; i++) {
System.out.println("new Array Elements are=" + resultantArray[i]);
}

}
Output:
new Array Elements are=10
new Array Elements are=20
3. asList() Method
asList( ) method is used to convert an array to a list.

Syntax:

public static List asList(datatype[] array)

o This method receives an array of wrapper class as a parameter and then returns a list
of array elements.
o In a case if we pass an empty array, then it will throws NullPointerException.
o Here ‘datatype[]’ is the type of array (int[], float[], char[], double[], short[],
byte[], boolean[], long[]) you want to convert to List.

List of overloaded methods


-----------------------------------------
1. Public static List asList(int[] array)

2. public static List asList(float[] array)

3. public static List asList(char[] array)

4. public static List asList(double[] array)

5. public static List asList(long[] array)

6. public static List asList(byte[] array)

7. public static List asList(short[] array)

8. public static List asList(boolean[] array)

Example:

Get List from String Array


In the example, we have an array of some Strings. After calling Arrays.asList() we are
assigning it to List<String> list it means our array is converted to List<String> and this is
the way asList() method works

Examples:

package com.core.java.examples;

import java.util.Arrays;
import java.util.List;

public class StudyTonight {


public static void main(String[] args) {
String arr[] = new String[] { "Java", "C", "C++", "Python" };
List<String> list = Arrays.asList(arr);
System.out.println("List: " + list);
}
}
Output:

List: [Java, C, C++, Python]

Example: Get List from Integer Array

Similar to the above example here we used Integer class. In the code given below, we are converting an array of Integer class to a list of integers.

package com.core.java.examples;

import java.util.Arrays;
import java.util.List;
public class StudyTonight
{
public static void main(String[] args)
{
Integer arr[]= new Integer[] { 12, 34, 22, 87, 98 };
List<Integer> list = Arrays.asList(arr);
System.out.println("List of Integers: " + list);
}
}

Output:
List of Integers: [12, 34, 22, 87, 98]

Example: Get List from Several Type of Arrays

In this example, we have several arrays of type float, byte, short, etc and get list of each
type by using the asList() method of Arrays class.

package com.core.java.examples;

import java.util.Arrays;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
Float arr1[]= new Float[] { 12.5f, 34.2f, 22.22f, 87.1f, 98.3f };
List<Float> list1 = Arrays.asList(arr1);
System.out.println("List of Integers: " + list1);

Byte arr2[]= new Byte[] { 12, 34, 22, 87, 98 };


List<Byte> list2 = Arrays.asList(arr2);
System.out.println("List of Bytes: " + list2);

Boolean arr3[]= new Boolean[] { true, false, false};


List<Boolean> list3 = Arrays.asList(arr3);
System.out.println("List of Booleans: " + list3);

Short arr4[]= new Short[] { 12, 34, 22, 87, 98 };


List<Short> list4 = Arrays.asList(arr4);
System.out.println("List of Shorts: " + list4);
}
}
output:
List of Integers: [12.5, 34.2, 22.22, 87.1, 98.3]
List of Bytes: [12, 34, 22, 87, 98]
List of Booleans: [true, false, false]
List of Shorts: [12, 34, 22, 87, 98]

Conclusion:
o The asList() method is used to convert array to list of elements.
o This method accepts an array and returns a list of that specified array.
o This method can be called without creating an object as this is the static method
we can directly call it over a class name.

4. sort() Method
o sort() method is used to sort, the elements/values of given array in Ascending Order.
o syntax:
public static void sort(datatype[] array)
o List of Overloading Methods of sort() Method
===================================
1. public static void sort(int[] array1)
2. public static void sort(long[] array2)
3. public static void sort(float[] array3)
4. public static void sort(double[] array4)
5. public static void sort(char[] array5)
6. public static void sort(byte[] array6)
7. public static void sort(short[] array7)
8. public static void sort(boolean[] array8)

We can extend the feature of this sort( ) method by providing a range of an array
with startIndex and endIndex.
Let's see its syntax and examples.
o Syntax:
public static void sort(datatype[] array,fromIndex,toIndex)
o List of Overloading Methods of sort() Method
=================================================================
9. public static void sort(int[] array1,fromIndex,toIndex)
10. public static void sort(long[] array2,fromIndex,toIndex)
11. public static void sort(float[] array3,fromIndex,toIndex)
12. public static void sort(double[] array4,fromIndex,toIndex)
13. public static void sort(char[] array5,fromIndex,toIndex)
14. public static void sort(byte[] array6,fromIndex,toIndex)
15. public static void sort(short[] array7,fromIndex,toIndex)
16. public static void sort(boolean[] array8,fromIndex,toIndex)

Example of sort() method


-----------------------------------------
In the following example, we can see sort() method is accepting array, which is unsorted
initially and this method sorts it in ascending order.

package com.core.java.examples;

import java.util.Arrays;
class StudyTonight {
public static void main(String args[])
{
int arr[] = {10, 8, 12, 1, 12, 5, 16, 4, 10, 3, 14, 11, 20, 17, 18};
System.out.println("Array Before Sorting ");
for(int num:arr)
{
System.out.print(num+" ");
}
Arrays.sort(arr);
System.out.println("\nArray After Sorting ");
for(int num:arr)
{
System.out.print(num+" ");
}
}

Output:
Array Before Sorting
10 8 12 1 12 5 16 4 10 3 14 11 20 17 18
Array After Sorting

1 3 4 5 8 10 10 11 12 12 14 16 17 18 20

Example of float:

package com.core.java.examples;

import java.util.Arrays;
class StudyTonight {
public static void main(String args[])
{
float arr[] = {10.3f, 8.2f, 12.4f, 1.3f, 12.2f, 5.1f, 16.6f, 4.4f, 10.2f, 3.6f, 14.1f,
11.1f, 20.2f, 17.1f, 18.1f};
System.out.println("Array Before Sorting ");
for(float num:arr)
{
System.out.print(num+" ");
}
Arrays.sort(arr);
System.out.println("\nArray After Sorting ");
for(float num:arr)
{
System.out.print(num+" ");
}
}

Similarly you can write for double, char, long, short, byte and boolean.

Programs:
---------
Questions:

----------------

1. write a program to sort the given double[] array is ascending order

double[] x={10.22,30.33,2.44,3.66,5.88,12.56};

2. write a program to sort the given double[] array is ascending order

char[] x={'a','b','A','m','B','D'};

3. write a program to sort the given long[] array is ascending order

char[] x={770,'b','A','m','B','D'};

5. binarySearch() Method
• This method belongs to the Arrays class in Java, and it is very helpful to search a key in
large arrays.

• BinarySearch without using comparator


-----------------------------------------
Syntax:
1. Pubic static return-type binarySearch(T[] a, T key)
Here ‘T’ is the type of array (i.e int, float, char, double, long, short,
byte) in which ever array you want perform search operation you have to give that
array.
• The second parameter will be the key which we want to search
List of Overloading Methods of binarySearch() Method
---------------------------------------------------------

1) Pubic static int binarySearch(int[] a, int key)


2) Pubic static int binarySearch(int[] a, int key)
3) Pubic static int binarySearch(int[] a, int key)
4) Pubic static int binarySearch(int[] a, int key)
5) Pubic static int binarySearch(int[] a, int key)
6) Pubic static int binarySearch(int[] a, int key)
7) Pubic static int binarySearch(int[] a, int key)
8) Pubic static int binarySearch(int[] a, int key)

Example: The binarySearch() Without a Comparator


In the example given below, we are using Arrays.binarySearch() on an array that is sorted in
ascending order. This method will return an index of a key element.
package com.core.java.examples;

import java.util.Arrays;

public class StudyTonight {


public static void main(String[] args) {
int array[] = { 2, 6, 7, 8, 13, 19, 27, 55, 80 };
int key = 19;
int index = Arrays.binarySearch(array, key);
System.out.print(key + " found at index: " + index);
}
}
Output:
19 found at index: 5

package com.core.java.examples;

import java.util.Arrays;

public class StudyTonight {


public static void main(String[] args) {
char array[] = { 'a','b', 'c', 'd', 'd','e', 'f','g', 'h' };
char key = 'h';
int index = Arrays.binarySearch(array, key);
System.out.print(key + " found at index: " + index);
}
}
Output:
‘h’ found at index: 8

Questions:
-----------
1. Write a program to sort an array, and find the 40 element, and return the index position of
an element 40?
Answer:
package com.core.java.examples;

import java.util.Arrays;

public class StudyTonight {


public static void main(String[] args) {

int[] numbers = { 10, 20, 30, 50, 60, 40, 80, 90, 110 };
System.out.println("Array before Sorting");
for (int i : numbers) {
System.out.print(i + "");
}
System.out.println("");
Arrays.sort(numbers);
System.out.println("After Sorting");
for (int i : numbers) {
System.out.print(i + "");
}
}
}
1. Write a program to sort an array, and find the 50 element, and return the index position
of an element 50?
Int[] a={10,20,30,40,50,80,100,90,120,110,85,65};
2. Write a program to sort an array, and find the 90 element, and return the index position
of an element 90?
Int[] a={10,20,30,40,50,80,100,90,120,110,85,65};
3. Write a program to sort an array, and find the 80 element, and return the index position
of an element 80?
Int[] a={10,20,30,40,50,80,100,90,120,110,85,65};
4. Write a program to sort an array, and find the 90 element, and return the index position
of an element 90?
Int[] a={10,20,30,40,50,80,100,90,120,110,85,65};
5. Write a program to sort an array, and find the 50 element, and return the index position
of an element 50?
Long[] a={10,20,30,40,50,80,100,90,120,110,85,65};
6. Write a program to sort an array, and find the 90 element, and return the index position
of an element 90?
Char[] a={10,20,30,40,50,80,100,90,120,110,85,65};
7. Write a program to sort an array, and find the 80 element, and return the index position
of an element 80?
Int a={10,20,30,40,50,80,100,90,120,110,85,65};
8. Write a program to sort an array, and find the 90 element, and return the index position
of an element 90?
Int a={10,20,30,40,50,80,100,90,120,110,85,65};
o Syntax:
2. Pubic static returntype binarySearch(T[] a, T key, Comparator<? super T> c)
• Here ‘T’ is the type of array (i.e int, float, char, double, long, short, byte) in
which ever array you want perform search operation you have to give that array.
• The second parameter will be the key which we want to search
• The third parameter will be the comparator to set the order in which the array is
sorted.
By default, array is sorted in ascending order.

List of Overloading Methods of binarySearch() Method


========================================================================

• public static int binarySearch(int[] a, int key, Comparator c)


• public static float binarySearch(float[] a, float key, Comparator c)
• public static char binarySearch(char[] a, char key, Comparator c)
• public static double binarySearch(int[] a, double key, Comparator c)
• public static long binarySearch(long[] a, long key, Comparator c)

Examples:
package com.core.java.examples;

import java.util.Arrays;
import java.util.Comparator;
public class StudyTonight
{
public static void main(String[] args)
{
Integer array[]={90, 55, 49, 42, 33, 25, 8, 6, 1};
Integer key = 33;
int index = Arrays.binarySearch(array, key, new Comparator<Integer>(){
public int compare(Integer o1, Integer o2) {
if(o1>o2)
{
return 1;
}
else
{
return 0;
}
}
});
System.out.print(key+" found at index: "+index);
}

Output:
33 found at index: 4

What if we do not want to perform the binary search on the whole array? In that case, we
must pass the beginning index i.e fromIndex and the ending index i.e toIndex,

Syntax:
public binarySearch(T[] a, fromIndex, toIndex, T key)

List of Overloading Methods of binarySearch() Method

===========================================================================

1. public static binarySearch(int[] a, int fromIndex, int toIndex, int key)


2. public static binarySearch(float[] a, int fromIndex, int toIndex, int key)
3. public static binarySearch(double[] a, int fromIndex, int toIndex, int key)
4. public static binarySearch(long[] a, int fromIndex, int toIndex, int key)
5. public static binarySearch(double[] a, int fromIndex, int toIndex, int key)
6. public static binarySearch(short[] a, int fromIndex, int toIndex, int key)
7. public static binarySearch(byte[] a, int fromIndex, int toIndex, int key)

overloaded methods of binarySearch()


package com.core.java.examples;

import java.util.Arrays;
public class StudyTonight
{
public static void main(String[] args)
{
byte byteArray[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60};
char charArray[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'};
int intArray[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150};
double doubleArray[] = {5.1, 6.2, 7.2, 8.1, 9.4, 10.2, 11.6, 12.96, 13.2, 14.25, 15.6, 16.4, 17.2};
float floatArray[] = {1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f};
short shortArray[] = {2, 4, 6, 8, 10 ,12, 14, 16, 18, 20};

byte byteKey = 25;


//Example of static int binarySearch(byte[] a, byte key)
System.out.println(byteKey + " found at index = "+Arrays.binarySearch(byteArray,byteKey));
//Example of static int binarySearch(byte[] a, int fromIndex, int toIndex, byte key)
System.out.println(byteKey + " found at index = "+Arrays.binarySearch(byteArray,0,7,byteKey));

char charKey = 'd';


//Example of static int binarySearch(char[] a, char key)
System.out.println(charKey + " found at index = "+Arrays.binarySearch(charArray,charKey));
//Example of static int binarySearch(char[] a, int fromIndex, int toIndex, char key)
System.out.println(charKey + " found at index = "+Arrays.binarySearch(charArray, 3, 8, charKey));

int intKey = 130;


//Example of static int binarySearch(int[] a, int key)
System.out.println(intKey + " found at index = "+Arrays.binarySearch(intArray, intKey));
//Example of static int binarySearch(int[] a, int fromIndex, int toIndex, int key)
System.out.println(intKey + " found at index = "+Arrays.binarySearch(intArray, 0, 5, intKey));

double doubleKey = 15.6;


//Example of static int binarySearch(double[] a, double key)
System.out.println(doubleKey + " found at index = "+Arrays.binarySearch(doubleArray,doubleKey));
//Example of static int binarySearch(double[] a, int fromIndex, int toIndex, double key)
System.out.println(doubleKey + " found at index = "+Arrays.binarySearch(doubleArray, 1, 5, doubleKey));

float floatKey = 9f;


//Example of static int binarySearch(float[] a, float key)
System.out.println(floatKey + " found at index = "+Arrays.binarySearch(floatArray, floatKey));
//Example of static int binarySearch(float[] a, int fromIndex, int toIndex, float key)
System.out.println(floatKey + " found at index = "+Arrays.binarySearch(floatArray, 0, 5, floatKey));

short shortKey = 16;


//Example of static int binarySearch(short[] a, short key)
System.out.println(shortKey + " found at index = "+Arrays.binarySearch(shortArray, shortKey));
//Example of static int binarySearch(short[] a, int fromIndex, int toIndex, short key)
System.out.println(shortKey + " found at index = "+Arrays.binarySearch(shortArray, 2, 8, shortKey));
}
}

Output:
25 found at index = 4
25 found at index = 4
d found at index = 3
d found at index = 3
130 found at index = 12
130 found at index = -6
15.6 found at index = 10
15.6 found at index = -6
9.0 found at index = 8
9.0 found at index = -6
16 found at index = 7
16 ound at index = 7
parallelSort() Method
This sorting technique is very fast because it works parallelly to sort elements of
the given array.
syntax:
public static void parallelSort(datatype[] array)
this method accepts the array as a parameter and return the sorted array.
List of Overloading Methods of binarySearch() Method
-----------------------------------------------------

1. public static void parallelSort(int[] array)


2. public static void parallelSort(long[] array)
3. public static void parallelSort(float[] array)
4. public static void parallelSort(double[] array)
5. public static void parallelSort(char[] array)
6. public static void parallelSort(byte [] array)
7. public static void parallelSort(short[] array)
8. public static void parallelSort(boolean[] array)

example of parallelSort by passing int[]


package com.core.java.examples;

import java.util.Arrays;
class StudyTonight {
public static void main(String args[])
{
int arr[] = {1, 46, 165, 6, 78, 6, 65, 955, 4, 5, 323, 256, 5, 99, 22, 33};
//sorting an array
Arrays.parallelSort(arr);
for(int num:arr)
{
System.out.print(num+" ");
}
}
}

Output:

1 4 5 5 6 6 22 33 46 65 78 99 165 256 323 955

Programs to practice:

1. Write a java program to sort the given array 100,99,300,250,110,500,450 using


parallelsorting techniche.

2. Write a java program to sort the given array 100,99,300,250,110,500,450 using


parallelsorting techniche.

3. Write a java program to sort the given array


100.2f,99.3f,300.3f,250.1f,110.1f,500.5f,450.4f using parallelsorting techniche.

4. Write a java program to sort the given array 10.1f,99.9f,3.6f,2.5f,1.1f,5.3,4.5f using


parallelsorting techniche.

5. Write a java program to sort the given array 'a','b','C','A','B','c' using


parallelsorting techniche.

6. Write a java program to sort the given array 'N','S','K','A','B','c' using


parallelsorting techniche.

7. Write a java program to sort the given array


100.345,99.99,300.001,250.255,110.11,500.52,450.40 using parallelsorting techniche.

8. Write a java program to sort the given array


10.12,99.22,300.33,250.25,110.11,500.55,450.45 using parallelsorting techniche.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy