Showing posts with label Array. Show all posts
Showing posts with label Array. Show all posts

Rotate array by N elements

Given an array, cyclically rotate the array clockwise by N elements. The conditions are 

  • Should NOT use temporary array to store values
  • N should be > 0 and <= given array size
Sample:

Array Rotate

We will see how to rotate the array by two ways.

  • 1st lets see simple solution that takes 1st element and swap with last element for N times and each time array values will be moved 1 position front like arr[i] = arr[i+1]
  • 2nd lets see swapping 0th to xth all elements, next swapping all from xth to last element and finally swapping all elements from 0th to last element with 3 for loops independently. 


METHOD-1:

public class ArrayRotate {

 public static void main(String[] args) {

  int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

  printArray("BEFORE ROTATE :::: ", array);

  rotate(array, 5);

  printArray("AFTER ROTATE ::::: ", array);

 }

 private static void printArray(String txt, int array[]) {
  System.out.print(txt + " ::: ");
  for (int i : array) {
   System.out.print(i + ", ");
  }
  System.out.println();
 }

 private static void rotate(int[] array, int startLoc) {

  if (startLoc < 0 || startLoc > array.length) {
   System.out.println("Out of array index !!!");
   return;
  }

  for (int i = 0; i < startLoc - 1; i++) {
   int tmp = array[0];
   for (int j = 0; j < array.length - 1; j++) {
    array[j] = array[j + 1];
   }
   array[array.length - 1] = tmp;
  }
 }
}

OUTPUT:

BEFORE ROTATE ::::  ::: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
AFTER ROTATE :::::  ::: 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 



METHOD-2:


public class RotateArray {

 public static void main(String[] args) {

  int array[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };

  printArray("BEFORE ROTATE :::: ", array);

  rotate(array, 5);

  printArray("AFTER ROTATE ::::: ", array);

 }

 private static void printArray(String txt, int array[]) {
  System.out.print(txt + " ::: ");
  for (int i : array) {
   System.out.print(i + ", ");
  }
  System.out.println();
 }

 private static void rotate(int[] array, int startLoc) {
  
  if (startLoc < 0 || startLoc > array.length) {
      System.out.println("Out of array index !!!");
      return;
  }
  
  for(int i=0,j=startLoc-2;i<j;i++,j--) {
   int tmp = array[i];
   array[i] = array[j];
   array[j] = tmp;
  }
  
  for(int i=startLoc-1,j=array.length-1;i<j;i++,j--) {
   int tmp = array[i];
   array[i] = array[j];
   array[j] = tmp;
  }

  for(int i=0,j=array.length-1;i<j;i++,j--) {
   int tmp = array[i];
   array[i] = array[j];
   array[j] = tmp;
  }
 }
}


OUTPUT:


BEFORE ROTATE ::::  ::: 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 
AFTER ROTATE :::::  ::: 15, 16, 17, 18, 19, 20, 11, 12, 13, 14, 

Array with Even and Odd numbers

Array with Even and Odd numbers

This is one of the interesting interview question which asked about integer array. Before going into direct question please refer to other tutorial about Java Array which we discussed earlier. 

There is an integer array with combination of Even and Odd numbers. Numbers are un-ordered and need to arrange all even numbers left and all odd numbers at right side with ascending order respectively ie., all even numbers at left side and all odd numbers at right should to sorted separately. For example if the input array is {4,6,1,5,8,3,2,7,9}, then output should be {2,4,6,8,1,3,5,7,9}
The constraints are 
  • Should not use any additional array
  • Should not use any collection API
Need to arrange and sort integers in same array. Lets see Java solution for this program by sorting and arranging integers.


public class EvenOddArray {

 public static void main(String[] args) {

  int[] array = new int[] {31, 30, 4, 6, 8, 3, 2, 7, 9, 12, 34, 11 };

  int evenPnt = 0;
  
  // Arranging Even and Odd numbers
  for (int i = 0; i < array.length; i++) {
   if (array[i] % 2 == 0) {
    swap(array, evenPnt, i);
    evenPnt++;
   }
  }
  
  // Sorting even numbers
  sort(array, 0, evenPnt);
  
  // Sorting Odd numbers 
  sort(array, evenPnt, array.length);

  for (int i : array) {
   System.out.print(i+", ");
  } 
 }

 public static void sort(int[] arr, int min, int max) {
  for (int i = min; i < (max - 1); i++) {
   for (int j = i + 1; j < max; j++) {
    if (arr[i] > arr[j]) {
     swap(arr, i, j);
    }
   }
  }
 }

 public static void swap(int[] arr, int i, int j) {
  int tmp = arr[i];
  arr[i] = arr[j];
  arr[j] = tmp;
 }
}


OUTPUT:


2, 4, 6, 8, 12, 30, 34, 3, 7, 9, 11, 31, 

Array in Java

Array in Java

Array is a simple Data Structure as same as which we have read in C, C++. If we need to describe then, "Array is a container which holds fixed no. of values of 1 data type (ie., If its Integer array then we can't store Character or String in it)". Size of the array must be defined at the time of array creation and its fixed until and unless if we try to re-create same array with different size. Lets see simple String array creation example in java.


public class ArrayTest {
 
 public static void main(String[] args) {
  
  // Creating Array with size 5
  String[] array = new String[5];
  
  array[0] = "java";
  array[1] = "J2EE";
  array[2] = "Servlet";
  array[3] = "JSP";
  array[4] = "Web Services";
  
  // Which gives runtime exception
  // ArrayIndexOutOfBoundsException
  //array[5] = "java";
  
  System.out.println("array[0] - "+array[0]);
  System.out.println("array[1] - "+array[1]);
  System.out.println("array[2] - "+array[2]);
  System.out.println("array[3] - "+array[3]);
  System.out.println("array[4] - "+array[4]);
 }
}


OUTPUT: 


array[0] - java
array[1] - J2EE
array[2] - Servlet
array[3] - JSP
array[4] - Web Services


As we seen in above example we can't assign values to "array[5]", since we have created array with the size of 5 and we are trying to store value beyond its size. So we will get run-time exception call ArrayIndexOutOfBoundsException.


Multi-Dimensional Array:

Above we have seen about single dimensional array creation with example. In Java we can use Multi-Dimensional array also as like below.


public class ArrayTest {
 
 public static void main(String[] args) {
  
  String names[][] = { {"thread", "array", "collection"}, 
        {"jsp", "servlet"}, 
        {"SOAP", "RESTFull"} 
          };
  
  System.out.println("names[0][0] - "+ names[0][0]);
  System.out.println("names[1][1] - "+ names[1][1]);
  System.out.println("names[2][0] - "+ names[2][0]);
  System.out.println("names[0][3] - "+ names[0][2]);
  
 } 
}


OUTPUT:


names[0][0] - thread
names[1][1] - servlet
names[2][0] - SOAP
names[0][3] - collection



Array Types:

Not only String we can create array with all primitve and non-primitive data types in Java as like below. 


int[] _int = new int[5];
char[] _char = new char[2];
float[] _flat = new float[4];
Integer[] _Integer = new Integer[5];
Boolean[] _Boolean = new Boolean[4];




Copying array values to another array:

System class method arraycopy() is used to copy array values from 1 array (source) to another array (destination). Both source and destination array must be same data type. arraycopy() method contains 5 parameters like
src - Source array
srcPos - Source array position to copy
dest - Destination array
destPos - Destination array position to be copied 
length - Length of array to copy 

Below is a simple example to copy array value from 1 array to another array.


public class ArrayTest {
 
 public static void main(String[] args) {
  
  int[] _intSrc = new int[]{0,11,12,13,14,15,16,17,18,19};
  
  int[] _intDes = new int[5];
  
  _intDes[0] = 99;
  
  // Copying values from 11 to 14
  System.arraycopy(_intSrc, 1, _intDes, 1, 4);
  
  for (int val : _intDes) {
   System.out.println(val);
  }
 } 
}


OUTPUT:


99
11
12
13
14



Another way of copying values from 1 array to another array using java.util.Arrays() class. Method called copyOfRange() used to copy specific array elements to another array same like below example code.


import java.util.Arrays;

public class ArrayTest {
 
 public static void main(String[] args) {
  
  int[] _intSrc = new int[]{0,11,12,13,14,15,16,17,18,19};
  
  // Copying from _intSrc (Range index 2 to 7)
  int[] _intDes = Arrays.copyOfRange(_intSrc, 2, 7);
  
  for (int val : _intDes) {
   System.out.println(val);
  }
 } 
}


OUTPUT:


12
13
14
15
16