Thursday, 5 May 2016

Merging two sorted arrays using Java ....

here is the code .....


       
public class MergingSortedLists {

 public static void main(String args[]) {

  int[] arr1 = {
   1,
   4,
   5,
   43,
   56,
   59
  };
  int[] arr2 = {
   2,
   3,
   6,
   34,
   36,
   42,
   67
  };
  int[] sortedList = new int[arr1.length + arr2.length];
  mergeLists(arr1, arr2, sortedList);
 }

 public static void mergeLists(int[] arr1, int[] arr2, int[] sortedList) {
  int k = 0;
  int j = 0;
  int t = 0;
  while (k < arr1.length && j < arr2.length) {
   if (arr1[k] <= arr2[j]) {
    sortedList[t] = arr1[k];
    t++;
    k++;
   } else {
    sortedList[t] = arr2[j];
    t++;
    j++;
   }
  }
  if (k != arr1.length) { //case where arr1 is left with elements not added to sorted list
   while (k < arr1.length) {
    sortedList[t] = arr1[k];
    t++;
    k++;
   }
  }
  if (j != arr2.length) { //case where arr2 is left with elements not added to sorted list
   while (j < arr2.length) {
    sortedList[t] = arr2[j];
    t++;
    j++;
   }
  }
  for (int s: sortedList) {
   System.out.print(s);
   System.out.print(" ");

  }
 }
}

       
 

Wednesday, 4 May 2016

Check whether two numbers are of opposite signs or not using Java .....

Problem -Two numbers are given ,you have to evaluate whether they are of opposite signs or not

Logic -Numbers are represented in 2's complemented form in computer where sign bit 0 means it is 
            positive number and 1 means it is negative .

here is the code ......


       
public class CheckOppositeSigns {

 public static void main(String args[]) {
  int x = 2;
  int y = -13;
  if (checkForOppositeSigns(x, y))
   System.out.print("Yes both the integers are of opposite signs");
  else
   System.out.print("Both the integers are of same sign");
 }

 public static boolean checkForOppositeSigns(int x, int y) {

  int signofFirstVariable = (x >> 31) ^ (0x1); //shifting the variable to place the sign bit at unit                                                                                     //position and then XOR with 000000000
  int signofSecondVariable = (y >> 31) ^ (0x1);
  if (signofFirstVariable != signofSecondVariable)
   return true;

  return false;
 }
}

       
 

Wednesday, 27 April 2016

Binary Search Tree implemented using Java ....

Binary Search Tree -

A binary search tree is a rooted binary tree, whose internal nodes each store a key (and optionally, an associated value) and each have two distinguished sub-trees, commonly denoted left and right. The tree additionally satisfies the binary search tree property, which states that the key in each node must be greater than all keys stored in the left sub-tree, and smaller than all keys in right sub-tree.[1]:287 (The leaves (final nodes) of the tree contain no key and have no structure to distinguish them from one another. Leaves are commonly represented by a special leaf or nil symbol, a NULL pointer, etc.)

here is the code ....



       
public class BinarySearchTreeImplementation {

 public static void main(String args[]) {

  BinarySearchTree tree = new BinarySearchTree();
  tree.addNode(50);
  tree.addNode(10);
  tree.addNode(100);
  tree.addNode(20);
  tree.addNode(200);
  tree.addNode(99);
  System.out.println("Binary Search Tree after the insertion of the nodes");
  tree.printBSTPreOrder();
 }

}

class BinarySearchTree {

 Node root;

 class Node {
  int data;
  Node leftChild;
  Node rightChild;

  Node(int d) {
   data = d;
   leftChild = null;
   rightChild = null;
  }
 }

 public void addNode(int d) {
  Node new_node = new Node(d);
  Node temp;
  if (root != null) {
   temp = root;
   Node parent_node = findPositionForNodeToAdd(temp, d);
   if (parent_node.data < d)
    parent_node.rightChild = new_node;
   else
    parent_node.leftChild = new_node;

  } else {
   root = new_node;
  }
 }

 public Node findPositionForNodeToAdd(Node root, int d) {

  if (root.leftChild == null && root.rightChild == null)
   return root;
  else if (root.data >= d) {
   if (root.leftChild != null)
    return findPositionForNodeToAdd(root.leftChild, d);
   else
    return root;
  } else if (root.data < d) {
   if (root.rightChild != null)
    return findPositionForNodeToAdd(root.rightChild, d);
   else
    return root;
  }

  return null;
 }

 //Prints the binary search tree in pre order traversal
 public void printBSTPreOrder() {
  if (root == null)
   System.out.println("Binary Search Tree is empty till now");
  else {
   Node temp = root;
   preOrder(temp);
  }
 }

 private void preOrder(Node root) {
  if (root == null)
   return;
  else {
   System.out.print(root.data + " ");
   preOrder(root.leftChild);
   preOrder(root.rightChild);
  }
 }
}

       
 

Sunday, 24 April 2016

Sorting a Linked List contains only 0's,1's and 2's using Java ...

Problem - Given an unsorted Linked List containing values from the set {0,1,2}                       only sort it using java. 

Here is the code ....


       

public class SortLinkedList {

 public static void main(String[] args) {

  LinkedList list = new LinkedList();
  list.push(0);
  list.push(1);
  list.push(0);
  list.push(1);
  list.push(2);
  list.push(2);
  list.push(0);
  list.push(1);
  list.push(1);
  list.push(2);
  list.push(0);

  System.out.println("Before sorting");
  list.printList();
  System.out.println();
  list.sortList();
  System.out.println("After sorting");
  list.printList();
 }

}
class LinkedList {

 private Node head;

 class Node {
  int data;
  Node next;
  Node(int d) {
   next = null;
   data = d;
  }
 }

 public void push(int d) {

  Node new_Node = new Node(d);

  new_Node.next = head;
  head = new_Node; //Adding elements at the start of linked list
 }

 public void printList() {
  Node temp = head;
  while (temp != null) {
   System.out.print(temp.data);
   temp = temp.next;
   System.out.print(" ");
  }
 }
 public void sortList() {
  int[] count = new int[3];
  count[0] = 0;
  count[1] = 0;
  count[2] = 0;
  Node temp = head;
  while (temp != null) {
   if (temp.data == 0)
    count[0]++;
   else if (temp.data == 1)
    count[1]++;
   else count[2]++;
   temp = temp.next;
  }
  temp = head;
  int i = 0;
  while (temp != null) {
   if (count[i] == 0)
    i++;
   else {
    temp.data = i;
    temp = temp.next;
    count[i]--;
   }
  }
 }
}

       
 

Monday, 14 March 2016

Sort anagram strings using Java....

Problem Statement - Given a list of strings ,sort the list in such a fashion that anagrams are always                                       adjacent to each other.

here is the code ........

       
import java.io.*;
import java.util.*;

class sortanagram {

 public static boolean anagram(String arg1, String arg2) {
  int f;
  int[] arr = new int[256];
  if (arg1.length() == arg2.length()) {
   for (int i = 0; i < arg1.length(); i++) {
    f = arg1.charAt(i);
    arr[f] = arr[f] + 1;
   }

   for (int k = 0; k < arg2.length(); k++) {
    f = arg2.charAt(k);
    arr[f] = arr[f] - 1;
   }
   for (int d = 0; d < 256; d++) {
    if (arr[d] != 0) {
     return false;
    }

   }
   return true;
  } else {
   return false;
  }

 }

 public static void main(String args[]) {

  String[] args3 = {
   "abcd",
   "save",
   "dcba",
   "dog",
   "easv",
   "god",
   "free"
  };
  String temp;
  int p;

  for (int i = 0; i < args3.length; i++) {
   p = i;
   for (int l = i + 1; l < args3.length; l++) {
    if (anagram(args3[i], args3[l]) == true) {


     p++;
     temp = args3[l];
     args3[l] = args3[p];
     args3[p] = temp;

    }

   }

  }

  for (int r = 0; r < args3.length; r++)
   System.out.println(args3[r]);

 }

}

       
 

Friday, 11 March 2016

Prime number generator using Java....

Input Format- First line of input is number of test cases    //No. of Inputs

                        Second line contains two numbers separated by space ,all prime numbers generated                             will lie between them.
               
      e.g-            2                                //No. of Test cases
                        10 100                       //First test case
                        101 200                     //Second Case

here is the code ....

       
import java.io.*;
import java.util.*;
import java.lang.Math.*;

public class PrimeNumberGenerator {
 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);

  int[] primes = new int[4000];
  int numprimes = 0;

  primes[numprimes++] = 2;
  for (int i = 3; i <= 32000; i += 2) {
   boolean isprime = true;
   double cap = Math.sqrt(i) + 1.0;

   for (int j = 0; j < numprimes; j++) {
    if (j >= cap) break;
    if (i % primes[j] == 0) {
     isprime = false;
     break;
    }
   }
   if (isprime) primes[numprimes++] = i;
  }


  int T, N, M;

  T = in .nextInt();

  for (int t = 0; t < T; t++) {
   if (t > 0) System.out.println("");

   M = in .nextInt();
   N = in .nextInt();

   if (M < 2) M = 2;

   boolean[] isprime = new boolean[100001];
   for (int j = 0; j < 100001; j++) {
    isprime[j] = true;
   }

   for (int i = 0; i < numprimes; i++) {
    int p = primes[i];
    int start;

    if (p >= M) start = p * 2;
    else start = M + ((p - M % p) % p);

    for (int j = start; j <= N; j += p) {
     isprime[j - M] = false;
    }
   }

   for (int i = M; i <= N; i++) {
    if (isprime[i - M]) System.out.println(i);
   }
  }
 }
}

       
 

Thursday, 3 March 2016

Optimized Bubble Sort using Java .....

Quick Logic - In bubble sort we are compairing adjacent elements, swap them if we need to and this                          will continue upto (N-1) passes .So optimized bubble sort will be most efficient if the                          array is already sorted or almost sorted.

Optimization Logic - We are checking that if two continues passes of the bubble sort are same then                            we don't have to continue further because array has already become sorted till now.

here is the code....


       
public class OptimizedBubbleSort {

 static int[] arr = {
  1,
  2,
  3,
  4,
  5,
  6,
  70,
  18,
  9
 };
 static boolean[] swapFlag = new boolean[arr.length - 1]; //to keep track that in each pass swap happens or not
 static int temp;

 public static void main(String[] args) {

  bubbleSort();
  for (int i = 0; i < arr.length; i++) {
   System.out.print(arr[i] + " ");
  }
 }

 public static void bubbleSort() {

  for (int i = 0; i < arr.length - 1; i++) {
   for (int y = 0; y < arr.length - i - 1; y++) {
    if (arr[y] > arr[y + 1]) {
     swap(y, y + 1);
     swapFlag[i] = true;
    }
   }
   System.out.println(i + " pass");
   if (i != 0) {
    if (swapFlag[i] == false && swapFlag[i - 1] == false) //condition where we are checking that int two succesive passes
     return;
   }
  }
 }

 public static void swap(int k, int r) {
  temp = arr[r];
  arr[r] = arr[k];
  arr[k] = temp;
 }

}