Sunday, September 3, 2017

Java - Arrays Class

Source Link:
https://www.tutorialspoint.com/java/java_arrays.htm

Some Useful Methods: 

public static void sort(Object[] a)
Sorts the specified array of objects into an ascending order, according to the natural ordering of its elements. The same method could be used by all other primitive data types ( Byte, short, Int, etc.) 

public static void fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints. The same method could be used by all other primitive data types (Byte, short, Int, etc.)

public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive data types (Byte, short, Int, etc.)

public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, it returns ( – (insertion point + 1)).

Example:
https://www.tutorialspoint.com/java/util/arrays_binarysearch_int.htm 

package com.tutorialspoint;
import java.util.Arrays;
public class ArrayDemo {
   public static void main(String[] args) { 
 // initializing unsorted int array
   int intArr[] = {30,20,5,12,55}; 
 // sorting array
   Arrays.sort(intArr); 
 // let us print all the elements available in list
   System.out.println("The sorted int array is:");
   for (int number : intArr) {
   System.out.println("Number = " + number);
   } 
 // entering the value to be searched
   int searchVal = 12; 
   int retVal = Arrays.binarySearch(intArr,searchVal); 
   System.out.println("The index of element 12 is : " + retVal);
   }
}

Let us compile and run the above program, this will produce the following result:
The sorted int array is:
Number = 5
Number = 12
Number = 20
Number = 30
Number = 55
The index of element 12 is : 1

2 comments:

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...