Saturday, February 28, 2015

Array sort and search in a java pgm



Array sort and search

import java.util.Arrays;
 public class MainClass
{
   public static void main(String args[]) throws Exception
   {
      int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      int index = Arrays.binarySearch(array, 2);
      System.out.println("Found 2 @ " + index);
   }
   private static void printArray(String message, int array[])
   {
      System.out.println(message+ ": [length: " + array.length + "]");
      for (int i = 0; i < array.length; i++)
        {
         if(i != 0)
         {
            System.out.print(", ");
          }
              System.out.print(array[i]);                    
           }
              System.out.println();
          }
      }
 
 

Extending an Array in a java pgm



Extending an Array
public class Main
{
   public static void main(String[] args)
   {
      String[] names = new String[] { "A", "B", "C" };
      String[] extended = new String[5];
      extended[3] = "D";
      extended[4] = "E";
      System.arraycopy(names, 0, extended, 0, names.length);
      for (String str : extended)
      {
         System.out.println(str);
      }
   }
}
 

Array filling in a java pgm



Array filling
 
import java.util.*;
 public class FillTest 
{
   public static void main(String args[]) 
  {
      int array[] = new int[6];
      Arrays.fill(array, 100);
      for (int i=0, n=array.length; i < n; i++) 
      {
         System.out.println(array[i]);
      }
      System.out.println();
      Arrays.fill(array, 3, 6, 50);
      for (int i=0, n=array.length; i< n; i++) 
      {
         System.out.println(array[i]);
      }
   }
}