Sunday, January 15, 2012

Sorting and Searching using in build Arrays methods


import java.util.Arrays;
class Sorting
{
static void display(int array[])  //Static method for Displaying
{
for(int i=0;i<array.length;i++)
{
System.out.print(array[i]+" ");
}
System.out.println("");
}

public static void main(String args[])
{
int array[]=new int[10];

for(int i=0;i<10;i++)
array[i]=-3*i; //assigning some values in single dimensional array

System.out.println("Original contents:");  //Displaying original Contents
display(array);

Arrays.sort(array); //calling sort method to sort the contents
System.out.println("Sorted:");
display(array);

Arrays.fill(array,2,6,-1); //replacing the 0th position to 5th position with "-1"
System.out.println("After fil():");
display(array);

Arrays.sort(array); //sorting after inserting -1
System.out.println("After sorting:");
display(array);

System.out.println("The value -9 is at location"); //Searching the "-9" in the array by calling binary Search method
int index=Arrays.binarySearch(array,-9);
System.out.println(index);

}
}

Arrays


1. Two Dimentional Array Example

class ArrayDemo
{
public static void main(String args[])
{
int[]num={1,2,3,4,5}; //Single Dimensional Array
System.out.println("Array Length:" + num.length);

int k=0;
int [][] twoD=new int[4][5]; //Two Dimensional array (even columns)
for(int i=0;i<4;i++)
{
for(int j=0;j<5;j++)
{
twoD[i][j]=k;    //Storing 1 to 19 in two dimentional array
k++;
}

}

for(int i=0;i<4;i++)      //Displaying the elements from two dimentional array
{
for(int j=0;j<5;j++)
{
System.out.print(twoD[i][j]+"   ");
}
System.out.println();

}

}
}

Output:

Array Length:5
0   1   2   3   4
5   6   7   8   9
10   11   12   13   14
15   16   17   18   19

2. Two Dimensional (Uneven column) Array Example

public class Uneven
{
public static void main(String args[])
{
int [][] twoD=new int[4][];      //Two dimensional with Uneven columns array declaration
int k=0;
twoD[0]=new int[1];
twoD[1]=new int[2];
twoD[2]=new int[3];
twoD[3]=new int[4];
for(int i=0;i<4;i++)
{
for(int j=0;j<i+1;j++)
{
twoD[i][j]=k;
k++;
}
}

for(int i=0;i<4;i++)
{
for(int j=0;j<i+1;j++)
{
System.out.print(twoD[i][j]+" ");
}
System.out.println();
}
}
}

Output:

0
1 2
3 4 5
6 7 8 9