Category Archives: Data Structure

Array Data Structure and Complexity (Big-O)


“Array is collection (or group of) of homogeneous (same data type) items  referred to single variable, which store in contiguous space in memory.”

Note : Java works differently then they do in C/C++, In Java array elements are not stored in continuous locations.

For example: You have 10 integer numbers and want minimum, maximum and  average of these numbers. One way is take 10 variables and perform comparison and operations of these numbers. If numbers are in hundreds very difficult to deal with that because need to handle 100 variables. That’s what array come on picture to deal with same type data.

Points to remember:

  • Array always keep elements of same type such as primitive type or objects.
  • In Java array is dynamically allocated.
  • Array size always specified in int value not in short or long.
  • If number of elements in array are n ,then indexing of array start from 0…n-1.
  • Array is object in Java , if need to find  length, check for member length. To check length of array in C/C++ use sizeof.
  • Array can be use as static field, a local variable or a method parameter.
  • In java direct super class of Array is Object and implements java.lang.Cloneable and java.io.Serializable interface.
  • Time Complexity Access : Θ(1)
  • Time Complexity Search : Θ(n)
  • Time Complexity Insertion : Θ(n)
  • Time Complexity Deletion : Θ(n)
  • Space Complexity: O(n)

In data structure array are two types:

  • One dimensional arrays
  • Multi dimensional arrays

One Dimensional Array

One dimensional array also called as linear array.

Single Dimentional Array

Declaration of Array

Declaration show the reference of values as array and each value in array specified as type.

type var-name [];
or
type [] var-name;

Example to declare array of different types.

// both are valid way of declarations
int numbers[];
or int[] numbers; 

byte byteArr[];
short shortsArr[];
boolean booleanArr[];
long longArr[];
<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>float floatArr[];
double doubleArr[];<span id="mce_SELREST_end" style="overflow:hidden;line-height:0;"></span>
char charArr[];

//array of reference objects of Class Type MyTestClass
MyTestClass myClassArray[]; 

//Array of unknown type object, as oBject is super class of class class
Object[]  objectArr,
//Array of unknown type of collection as Collection is super interface in Collection framework
Collection[] callectionArr;

Instantiation of Array

On array declaration only the reference of array created, to allocate memory to array need specified the size of array as below. where the size is always a integer value greater than zero.


var-name = new type[size];

For Example:

int numbers[]; //declaration
numbers=new int [10];//create an instance of array of 10 numbers.

Object[] objectArr; //declaration

objectArr=new Object[10]; //create an instance of array of 10 Objects.

Note:

  • For primitive type array instantiation, array elements values by default initialize with specified primitive default value. For example : primitive type int default value is 0, all the  elements array by default initialize with 0.
  • For reference type array instantiation, array element values by default initialize with specified primitive default value. For example : reference type Object default value is null, all the  elements array by default initialize with null.

Array Instantiation with Literals

If you already know the elements of an array , use literals in array to instantiation and assignment of values at same time.

//Array with int literals
int [] numbers={10,, 50, 70 , 90, 80};
//Array with String literals
String [] names= {"Saurabh", "Gaurav", "Raghav"};

Accessing of array

To access/assign the elements of an array, use index position within range 0 to n-1 for the size of array length n. If trying to access array beyond this range (0…n-1) for primitive and reference type, get an exception as ArrayIndexOutOfBoundException in case of String will throw StringIndexOutOfBoundsException


//accessing/assign value on array
arrName[index];

Example

//access value from array on index position 2, will result 70
int number=numbers[2];

//Assign value on index position , new change value 80
numbers[2]=80;

Java Program for Single Dimensional Array

Here is example of single line array , considering all above cases;


public class OneDimentionalArray {

	public static void main(String[] args) {

		//declaration by both ways
		int numbers[];

		//Instantion for array of int type size 10
		//By default initialize with 0 for primitive type int
		numbers=new int[10];

		//instantition with literals
		String []names= {"Saurabh","Gaurav","Raghav"};

		System.out.println("Print Numbers :");
		//access array with for loop
        for(int i=0; i<=numbers.length-1;i++)
		{
			System.out.println(numbers[i]);
		}

		System.out.println("\nPrint Name :");
		//access array with for each loop
		for(String name:names)
		{
			System.out.println(name);
		}

		// Assign values to Arrays by for loop
		for(int i=0; i<=numbers.length-1;i++)
		{
			numbers[i]=i*10;
		}

		//manually assign values,Raghav will replace with Ramesh
		names[2]="Ramesh";

		System.out.println("\n\nUpdate Values from arrays");

		//access array with for loop
                for(int i=0; i<=numbers.length-1;i++)
		{
			System.out.println(numbers[i]);
		}

		System.out.println("\nPrint Name :");
		//access array with for each loop
		for(String name:names)
		{
			System.out.println(name);
		}

	}

}

Output


Print Numbers :
0
0
0
0
0
0
0
0
0
0

Print Name :
Saurabh
Gaurav
Raghav


Update Values from arrays
0
10
20
30
40
50
60
70
80
90

Print Name :
Saurabh
Gaurav
Ramesh

Multi Dimensional Array

Multi-dimensional arrays also called Jagged Arrays, are arrays of arrays with each element of the array holding the reference of another array. A multi-dimensional array is created by appending square brackets ([]) per dimension.
For Example


int[][] intArr=new int [2][3]; //2D array
int numbers[][][]=new int [2][3][4]; //3D array

//2D representation with literals
//Create an array of size [2][3] and assign given values
int [][]numbers ={{2,5,7},{4,6,9}}

Two Dimentional Array

Java Program for Two Dimensional Array


public class TwoDimentionalArray1 {

	public static void main(String[] args) {

		//declaration
		int numbers[][] = {{2,5,7},{4,6,9}};

		//access in array of two dimensional array
        for(int i=0; i<=numbers.length-1;i++)
		{
        	for (int j=0; j<numbers[i].length;j++)
			System.out.println("numbers["+i+"]["+j+"]="+numbers[i][j]);
		}

		System.out.println("\n\nUpdate Values from arrays");

		numbers[0][1]=20;
		numbers[1][2]=30;
		numbers[0][0]=40;

		for(int i=0; i<=numbers.length-1;i++)
		{
        	for (int j=0; j<numbers[i].length;j++)
			System.out.println("numbers["+i+"]["+j+"]="+numbers[i][j]);
		}
	}

}

Output


numbers[0][0]=2
numbers[0][1]=5
numbers[0][2]=7
numbers[1][0]=4
numbers[1][1]=6
numbers[1][2]=9


Update Values from arrays
numbers[0][0]=40
numbers[0][1]=20
numbers[0][2]=7
numbers[1][0]=4
numbers[1][1]=6
numbers[1][2]=30

Advertisements

Merge Sort Program and Complexity (Big-O)


Mergesort is a comparison sort, same as quicksort and based on divide and conquer algorithm. It divides the original data set into smaller pieces of data set to solve the problem and then finally merge these small data sets.

How Merge Sort Works

Merge sort works in the following way:

  1. Merge sort, take middle index in data set and split into two collections : one collection for items left of middle index and second for right values of middle index.
  2. Repeat step 1 as long as these collections size reach to one item only.
  3. Now merge sort picks the items from smaller collections, sort them and merge to create new collection.
  4. Repeat this sort and merge process until all small colection sort and merge not completed.
  5. Finally will get single collection with sorted result.

Points to Remember

  • Data Structure: Array
  • Best Time Complexity: Ω(n log(n))
  • Average Time Complexity: Θ(n log(n))
  • Worst Time Complexity: O(n log(n))
  • Worst Space Complexity: O(n)

Merge Sort

Merge Sort Program

public class MergeSort {

    public int[] sort(int [] array){
     mergeSort(array, 0, array.length-1);
     return array;

    }

    private void mergeSort(int[] array, int first, int last) {

     // Get mid position to divide problem into smaller size collections
     int mid = (first + last) / 2;

     //If first < last the array must be recursively sorted
     if (first < last) {
      mergeSort(array, first, mid);
      mergeSort(array, mid + 1, last);
     }

     //merge solved collections to get solution to original problem
     int a = 0, f = first, l = mid + 1;
     int[] temp = new int[last - first + 1];

   //decide the swapping of items
     while (f <= mid && l <= last) {
      temp[a++] = array[f] < array[l] ? array[f++] : array[l++];
     }

     while (f <= mid) {
      temp[a++] = array[f++];
     }

     while (l <= last) {
      temp[a++] = array[l++];
     }

     a = 0;
     while (first <= last) {
      array[first++] = temp[a++];
     }
    }

    public static void printArray(int[] array) {
     for (int i = 0; i < array.length; i++) {
      System.out.print(array[i] + " ");
     }

    }

    public static void main(String[] args) {

     System.out.println("Original array before Merge sort");
     int[] items = {12, 24, 45, 56, 10, 9, 49, 30, 5, 15};
     printArray(items);

     System.out.println("\n\nAfter Mergesort");
     MergeSort merge = new MergeSort();
     merge.sort(items);
     printArray(items);

    }
}

Output


Original array before Merge sort
12 24 45 56 10 9 49 30 5 15 

After Mergesort
5 9 10 12 15 24 30 45 49 56 

 

Quicksort Program and Complexity (Big-O)


Quicksort is a comparison sort based on divide and conquer algorithm. Quick sort is more fast in comparison to Merge Sort ot Heap Sort. It’s not required additional space for sorting.

How Quick Sort Works

The idea to implement Quicksort is first divides a large array into two smaller sub-arrays as the low elements and the high elements then recursively sort the sub-arrays.

The above process follow below steps:

  1. If array having 0 or 1 item then it’s already sorted.
  2. Pick an item from the array that is called as pivot.
  3. Partition this array as items less than pivot will come before pivot while items greater than pivot will come after it (equals values can either way). Now Pivot get it’s exact position.
  4. Now repeat step 2 and 3 for both left and right side values of Pivot and continue same as long as no left or right items remaining.
  5. Finally, as result of array will sorted items.

Quicksort

Points to remember

  • Data Structure: Array
  • Best Time Complexity: Ω(n log(n))
  • Time Complexity: Θ(n log(n))
  • Worst Time Complexity: O(n^2)
  • Worst Space Complexity: O(log(n))

Quick Sort Program

public class QuickSort {

	public void quicksort(int[] array) {
		quicksort(array, 0, array.length - 1);
	}

	private void quicksort(int[] array, int first, int last) {
		if (first < last) {
			int pivot = partition(array, first, last);

			// Recursive call
			quicksort(array, first, pivot - 1);
			quicksort(array, pivot + 1, last);
		}
	}

	private int partition(int[] input, int first, int last) {

		//choose pivot as last item
		int pivot = last;

		swap(input, pivot, last);
		for (int i = first; i < last; i++) {
			if (input[i] <= input[last]) {
				swap(input, i, first);
				first++;
			}
		}

		swap(input, first, last);
		return first;
	}

	private void swap(int[] input, int a, int b) {
		int temp = input[a];
		input[a] = input[b];
		input[b] = temp;
	}

	public static void printArray(int[] items) {
		for (int i = 0; i < items.length; i++) {
			System.out.print(items[i] + " ");
		}
	}

	public static void main(String[] args) {

		int[] items = {12, 24, 45, 56, 10, 9, 49, 30, 5, 15};
		System.out.println("Original Array Before Quick Sort");
		printArray(items);

		System.out.println("\n\nAfter QuickSort");

		QuickSort sort = new QuickSort();
		sort.quicksort(items);
		printArray(items);

	}
}

Output


Original Array Before Quick Sort
12 24 45 56 10 9 49 30 5 15 

After QuickSort
5 9 10 12 15 24 30 45 49 56 

Radix Sort Program and Complexity (Big-O)


Radixsort sorts numeric data (integers or float) by considering a string of numbers where digit by digit sort starting from least significant digit position to most significant digit position. To sort these specific positions data counting sort as a subroutine.

Counting sort is a linear time sorting algorithm that sort in O(n+k) but that will worst in case of items range from 1 to n2 that sort in O(n^2). Where K is items range from 1 to k.

Note :

  • LSD : Least Significant Digit
  • MSD : Most Significant Digit

Steps to Radixsort

  1. Check for the max length item in input values and check for length.
  2. For each digit position i where i varies from LSD to the MSD.
  3. Perform counting sort based on considering key as i position digits.
  4. Finally, you will get a sorting array for input items.

Points to Remember

  • Data Structure: Array
  • Best Time Complexity: Ω(nk)
  • Average Time Complexity: Θ(nk)
  • Worst Time Complexity: O(nk)
  • Worst Space Complexity: O(n+k)

Radix sort Example


Input Numbers:

        170, 45, 75, 90, 02, 802, 2, 66 
Step 1 : Find the max item length in input i.e 3.

Step 2: Repeat the below process for position i from LSD to MSD
        Perform count sort on numbers, after considering digits as key on 
        particular i.
        
        0 Position :
        170, 90, 02, 802, 2, 45, 75, 66
        
        1 Position :
        02, 2, 802, 45, 66, 170, 75, 90
        
        2 Position :
        02, 2, 45, 66, 75, 90, 170, 802 
        
Step 3: Final Redix Sort result

        02, 2, 45, 66, 75, 90, 170, 802    
 

Radix Sort Program

public class RadixSort {

	public static void main(String[] args) {

		// Assuming our key values are with in range 0 - 9
		int[] items = { 170, 45, 75, 90, 02, 802, 2, 66 };
		System.out.println("Before Radix Sorting :");
		printArray(items);

		// Perform counting sort sort
		radixsort(items);

		System.out.println("After Radix Sorting :");
		printArray(items);
	}

	// radix sort method to sort values of array items
	static void radixsort(int items[]) {
		// find max number to know max number of digits
		int m = getMax(items);

		// Perform counting sort for every digit. Note that instead
		// of passing digit number, exp is passed. exp is 10^i
		// where i is current digit number
		for (int exp = 1; m / exp > 0; exp *= 10)
			countingsort(items, exp);
	}

	// A utility method to get maximum value in items[]
	static int getMax(int items[]) {
		int max = items[0];
		for (int i = 1; i  max)
				max = items[i];
		return max;
	}

	private static void countingsort(int[] items, int exp) {
		// create array of size 10 that will have index value as 0-9
		// it will create array of size 10 and initialize
		// each element with value 0
		int[] counts = new int[10];
		int[] output = new int[items.length];
		for (int key : items) {
			// for each match key, index position element
			// increase count as 1
			counts[(key / exp) % 10] += 1;
		}

		// Change count[i] so that count[i] now contains
		// actual position of this digit in output[]
		for (int i = 1; i = 0; i--) {
			output[counts[(items[i] / exp) % 10] - 1] = items[i];
			counts[(items[i] / exp) % 10] -= 1;
		}

		// Copy the output array to items[] to return
		// sorted array according to index position
		for (int i = 0; i < items.length; i++)
			items[i] = output[i];

	}

	static void printArray(int items[]) {
		for (int item : items) {
			System.out.print(item + " ");
		}
		System.out.println();
	}

}

Output


Before Radix Sorting :
170 45 75 90 2 802 2 66 
After Radix Sorting :
2 2 45 66 75 90 170 802 

Bucket Sort Program and Complexity (Big-O)


Bucket sort/Bin sort is a distribution sort as a generalization of pigeonhole sort. It’s useful when input values are uniformly distributed over a range then divide this range in some interval and put values in a bucket which lies within these intervals.Finally, sort values in each bucket by any sorting technique and then print by sequence by iterating intervals.

Bucket Sort Steps

  1. Set up an array of empty “buckets” initially.
  2. Go over the original array, putting each item in its interval bucket.
  3. Sort all non-empty bucket.
  4. Visit each interval buckets in order and put all elements back into the original array.

Points to Remember

  • Data structure: Array
  • Best Time Complexity: Ω(n+k)
  • Average Time Complexity: Θ(n+k)
  • Worst Time Complexity: O(n^2)
  • Worst Space Complexity: O(n)

Bucket Sort Java Program

public class BucketSort {

		public static void main(String[] args) {

			//Assuming our key values are with in range 0 - 1
			double[] items = { 0.23, 0.67, 0.32, 0.25, 0.88, 0.45, 0.86, 0.16, 0.59, 0.38, 0.19, 0.43,  0.02 };
	        System.out.println("Before Bucket Sorting :");
	        printArray(items);

	        //Perform counting sort sort
	        bucketsort(items);

	        System.out.println("After Bucket Sorting :");
	        printArray(items);
		}

		private static void bucketsort(double []items)
		{
			//create array of size 10 that will have index value as 0-9
			//Initially will keep empty bucket
			java.util.List []numbers=new ArrayList[10];
			for(double key:items)
			{
				//To equally distribute input values , multiply key with array size.
				int index=(int)(key*numbers.length);
				//index position is not having any value yet create blank bucket
				if(numbers[index]==null)
				{
					numbers[index]=new ArrayList();

				}
				//add items based on index position
				numbers[index].add(key);
			}

			//Now sort values in each bucket by any sorting method
			// and add in initial array
			int i=0;
			for(int index=0; index<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;">&#65279;</span>&lt;numbers.length; index++)
			{

				if(numbers[index]!=null)
				{
					//Here i am using Collections utility method but
					//you use any sorting algorithm.
					Collections.sort(numbers[index]);
					//iterate each value in sorted bucket
					//add it in original array position
					for(double  item:numbers[index])
					{
						items[i++]=item;
					}
				}

			}
		}

		static void printArray(double items[])
		{
	        for (double item:items)
	        {
	            System.out.print(item + &quot; &quot;);
	        }
	        System.out.println();
		}

}

Output


Before Bucket Sorting :
0.23 0.67 0.32 0.25 0.88 0.45 0.86 0.16 0.59 0.38 0.19 0.43 0.02 
After Bucket Sorting :
0.02 0.16 0.19 0.23 0.25 0.32 0.38 0.43 0.45 0.59 0.67 0.86 0.88 

Shell Sort Program and Complexity (Big-O)


Shellsort is an in-place comparison sort, also known as Shell sort or Shell’s method. It’s mainly variation of insertion sort or bubble sort . There was one drawback with insertion sort, we move elements only one position ahead but when an elements are too far then lots of movements are involved. To reduce these movements Shell sort come with idea of allow exchange of far items.

Shell Sort Steps

  • Pick some far location h and make sorted array for values index[h…n-1] by insertion sort.
  • Reduce the value of h until it becomes 1.
  • Repeat the steps 1 and 2
  • Finally you will get sorted items list.

Points to Remember

  • Data structure: Array
  • Worst-case performance: O(n2) (worst known worst case gap sequence) O(n log2n) (best known worst case gap sequence)
  • Best-case performance: O(n log n) (most gap sequences) O(n log2n)  (best known worst case gap sequence)
  • Average performance: depends on gap sequence
  • Worst-case space complexity : О(n) total, O(1) auxiliary

Sell Sort Java Program

public class ShellSort {
 public static void main(String[] args)
 {
		int[] items = { 2, 6, 3, 8, 4, 1, 5, 0 };
        System.out.println("Before Shell Sorting :");
        printArray(items);

        //Perform shell sort
        shellsort(items);

        System.out.println("After Shell Sorting :");
        printArray(items);
 }
 static void shellsort(int items[])
 {
     int n = items.length; 

     // Start with a big gap, then reduce the gap until 1
     for (int gap = n/2; gap > 0; gap /= 2)
     {
    	 //perform insertion sort for these gap size
    	 //The first gap elements a[0..gap-1] are already
    	 //in gapped order keep adding one more element
    	 //until the entire array is gap sorted 

         for (int i = gap; i = gap && items[j - gap] > temp; j -= gap)
            	 items[j] = items[j - gap]; 

             // put temp in its correct  location
             items[j] = temp;
         }
     } 

 } 

 static void printArray(int items[])
	{
     for (int item:items)
     {
         System.out.print(item + " ");
     }
     System.out.println();
	}
}

Output

 


Before Shell Sorting :
2 6 3 8 4 1 5 0 
After Shell Sorting :
0 1 2 3 4 5 6 8 

Counting Sort program & Complexity (Big-O)


Counting sort also called an integer sorting algorithm. Counting sort algorithm is based on keys in a specific range. It counts the number of items for distinct key value, use these keys to determine position or indexing on the array and store respective counts for each key. Finally, sort values based on keys and make sequences the repetition of key based on counts.

Counting sort is suitable where variation in keys are is not significantly greater than the number of items. Its running time is linear as numbers of items(n)+difference between max and min key values.

Points to Remember

  • Data structure: Array
  • Worst-case performance: O(n+k), where k is the range of the non-negative key values.
  • Worst-case space complexity: O(n+k)

Advantage

  • Counting sort is a stable sort, where if two items have the same key, they should have the same relative position in the sorted output as they did in the input.

Disadvantage

  • Data range should be predefined, if not then addition loops required to get min and max value to get range.
  • Not much variation on key values otherwise will occupy unnecessary space in the array.

Steps for Counting Sort


For easily understand, consider the data in the range 0 to 9 for below example:
Input data: 2, 6, 3, 2, 8, 4, 8, 1, 5, 3, 1, 4, 0
1) Create an array of size 10 (index values 0-9) and store the count of each 
   unique item.
  Index:     0  1  2  3  4  5  6  7  8  9
  Count:     1  2  2  2  2  1  1  0  2  0

2) Execute loop for each index for array and check counts are more than zero. 
   repeat the index/key value until count reach to zero. Store these values in 
   previous array and increase index position by one. Now sorted array
 
  Index:     0  1  2  3  4  5  6  7  8  9 10   11 12
  Count:     0  1  1  2  2  3  3  4  4  5  6   8  8

Counting Sort Program

public class CountingSort {

	public static void main(String[] args) {

		//Assuming our key values are with in range 0 - 9
		int[] items = { 2, 6, 3, 2, 8, 4, 8, 1, 5, 3, 1, 4, 0};
        System.out.println("Before Counting Sorting :");
        printArray(items);

        //Perform counting sort sort
        countingsort(items);

        System.out.println("After Count Sorting :");
        printArray(items);
	}

	private static void countingsort(int []items)
	{
		//create array of size 10 that will have index value as 0-9
		//it will create array of size 10 and initialize
		//each element with value 0
		int []numbers=new int[10];
		for(int key:items)
		{
			//for each match key, index position element
			//increase count as 1
			numbers[key]+=1;
		}

		//Now sort values based on keys and repeat
		//this key value as per count
		int i=0;
		for(int key=0; key0)
			{
				for(int count=1;count<=numbers[key];count++)
				{
					items[i++]=key;
				}
			}

		}
	}

	static void printArray(int items[])
	{
        for (int item:items)
        {
            System.out.print(item + " ");
        }
        System.out.println();
	}

}

Output


Before Counting Sorting :
2 6 3 2 8 4 8 1 5 3 1 4 0 
After Count Sorting :
0 1 1 2 2 3 3 4 4 5 6 8 8 

Heapsort Program and Complexity (Big-O)


Heapsort is a sorting algorithm based on a Binary Heap data structure. It’s a comparison-based sorting similar to Selection Sort where first find maximum item and place that maximum item at the end. Repeat the same steps for remaining items until all items sorted.

Points to Remember

  • Data structure: Array
  • Worst-case performance: O(n\log n)
  • Best-case performance : O(n\log n) (distinct keys) O(n) (equal keys)
  • Average performance: O(n\log n)
  • Worst-case space complexity: O(n) total O(1) auxiliary

See Also: Data Structure and Algorithms Complexity (Big-O)

Advantage

  • Heapsort is a more favorable in worst-case O(n log n) runtime.

Disadvantage

  • Heapsort slower in practice on most machines than a well-implemented quicksort.
  • Heapsort is not a stable sort but in-place algorithm.

Binary Heap Data Structure

Binary Heap is a type of Complete Binary Tree where items stored such a way like a parent node value is greater than the values of its child nodes. That is also called as Max heap. it can be represented in the form of a binary tree or array.

Binary Tree Representation in Array

To represent binary tree structure in the array, consider each array index as a node, where these index of nodes for a parent, left the child and right child follow these expression. In Binary tree for zero-based array ,the root node is stored at index 0; if i is the index of the current node, then

  • parent(i) = floor((i-1) / 2) , where floor map a real number to the smallest leading integer.
  • LeftChild(i) = 2*i + 1
  • RightChild(i) = 2*i + 2

Steps for Heap Sort

  1. Call the heapify() function on the array to make as Max Heap Binary Tree array where Maximum item on the first position.
  2. Swap the first item of the array with the final item. Consider the size of the array by decrease one. Call heapify() on the root of a binary tree.
  3. Repeat the above steps until the size of the unsorted heap is 1.

Note: The heapify() operation is run once, and is O(n) in performance. The swapping() function is O(log n) and is called n times. Therefore, the total performance of this heap sort algorithm is O(n + n log n) = O(n log n).

<h2>Heapsort Java Program</h2>
public class HeapSort {

 public static void main(String []args)
 {
	int[] items = { 2, 6, 3, 8, 4, 1, 5, 0 };
        System.out.println("Before Heap Sorting :");
        printArray(items);

        //Perform heap sort
        heapsort(items);

        System.out.println("After Heap Sorting :");
        printArray(items);
 }

 public static void heapsort(int items[])
 {
     int itemCount = items.length; 

     // Build heap (rearrange array)
     for (int i = itemCount / 2 - 1; i &gt;= 0; i--)
         heapify(items, itemCount, i); 

     // One by one extract an element from heap
     for (int i=itemCount-1; i&gt;=0; i--)
     {
         // Move max root item to end
         int temp = items[0];
         items[0] = items[i];
         items[i] = temp; 

         // call max heapify on the reduced heap
         heapify(items, i, 0);
     }
 } 

 /**
  * Call the heapify() function on the array of decrease size to make as Max Heap Binary
  * Tree array where Maximum item on first position or root.
  */
 static void heapify(int items[], int itemCount, int i)
 {
     int largest = i; // Initialize largest as root
     int l = 2*i + 1; // left = 2*i + 1
     int r = 2*i + 2; // right = 2*i + 2 

     // If left child is larger than root
     if (l  items[largest])
         largest = l; 

     // If right child is larger than largest so far
     if (r  items[largest])
         largest = r; 

     // If largest is not root
     if (largest != i)
     {
         int swap = items[i];
         items[i] = items[largest];
         items[largest] = swap; 

         // Recursively heapify the affected sub tree
         heapify(items, itemCount, largest);
     }
 } 

 static void printArray(int items[])
	{
     for (int item:items)
     {
         System.out.print(item + " ");
     }
     System.out.println();
	}
}

Output


Before Heap Sorting :
2 6 3 8 4 1 5 0 
After Heap Sorting :
0 1 2 3 4 5 6 8 

Data Structure and Algorithms Complexity (Big-O)


Big-O notation is a mathematical representation used to describe the complexity of a data structure and algorithm. There are two types of Complexity :

  1. Time Complexity: Its measure based on steps need to follow for an algorithm.
  2. Space Complexity: It measures the space required to perform an algorithm and data structure.

Data Structure and Algorithm Decision

Data structure and algorithm decisions are based on the complexity of size and operations need to perform on data. Some algorithms perform better on a small set of data while others perform better for big data sets for certain operations.

These days Space Complexity is not big concerns but the main performance of an algorithm measures based on time complexity. We can make the decision to choose an algorithm based on below performance criteria with respect to Complexity.

Complexity Performance
O(1) Excellent
O(log(n)) Good
O(n) Fair
O(n log(n)) Bad
O(n^2) Horrible
O(2^n) Horrible
O(n!) Horrible

This post almost covers data structure and algorithms space and time Big-O complexities. Here you can also see time complexities for types of operations like access, search, insertion, and deletion.

See also: 

Data Structure Space and Time Complexity

Data Structure Time Complexity Space Complexity
Average Worst
Access Search Insertion Deletion
Array Θ(1) Θ(n) Θ(n) Θ(n) O(n)
Stack Θ(n) Θ(n) Θ(1) Θ(1) O(n)
Queue Θ(n) Θ(n) Θ(1) Θ(1) O(n)
Singly-Linked List Θ(n) Θ(n) Θ(1) Θ(1) O(n)
Doubly-Linked List Θ(n) Θ(n) Θ(1) Θ(1) O(n)
Skip List Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n log(n))
Hash Table N/A Θ(1) Θ(1) Θ(1) O(n)
Binary Search Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)
Cartesian Tree N/A Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)
B-Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)
Red-Black Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)
Splay Tree N/A Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)
AVL Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)
KD Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)

Sorting Algorithms Space and Time Complexity

Algorithm Time Complexity Space Complexity
Best Average Worst Worst
Quick Sort Ω(n log(n)) Θ(n log(n)) O(n^2) O(log(n))
Merge Sort Ω(n log(n)) Θ(n log(n)) O(n log(n)) O(n)
Tim Sort Ω(n) Θ(n log(n)) O(n log(n)) O(n)
Heap Sort Ω(n log(n)) Θ(n log(n)) O(n log(n)) O(1)
Bubble Sort Ω(n) Θ(n^2) O(n^2) O(1)
Insertion Sort Ω(n) Θ(n^2) O(n^2) O(1)
Selection Sort Ω(n^2) Θ(n^2) O(n^2) O(1)
Tree Sort Ω(n log(n)) Θ(n log(n)) O(n^2) O(n)
Shell Sort Ω(n log(n)) Θ(n(log(n))^2) O(n(log(n))^2) O(1)
Bucket Sort Ω(n+k) Θ(n+k) O(n^2) O(n)
Radix Sort Ω(nk) Θ(nk) O(nk) O(n+k)
Counting Sort Ω(n+k) Θ(n+k) O(n+k) O(k)
Cube Sort Ω(n) Θ(n log(n)) O(n log(n)) O(n)

 

Selection Sort Program and Complexity (Big-O)


Selection sort is a simple sorting algorithm, it’s also known as in-place comparison sort. In selection sort algorithm, sorts an array of items by repeatedly finding the minimum item from unsorted part of array and move it at the beginning. This algorithm considers two sub arrays in a given array.

  1. The sub array of already sorted items.
  2. Remaining sub array unsorted items.

Points to remember

  • Data structure: Array
  • Worst-case performance : О(n2) comparisons and O(n)swaps
  • Best-case performance : O(n2) comparisons and O(n) Swaps
  • Average performance: О(n2) comparisons and O(n) Swaps
  • Worst-case space complexity :О(n) total, O(1) auxiliary

See Also : Data Structure and Algorithms Complexity (Big-O)

Advantage

  • Simple Implementation and efficient for small data set.
  • Efficient in  comparison to other Quadratic Sort (i.e O(n2)) like Bubble Sort or  Insertion Sort.
  • Efficient for data set that are already sorted. Time Complexity ( i.e O(n))
  • Not change relative order of elements which are already sorted. Space Complexity (i.e O(1))

Disadvantage

  • Selection sort is much less efficient on large lists in compare to algorithms such as quicksort, heapsort, or merge sort.

Selection Sort Steps

Here * marks the value set on particular iteration.

2 6 3 8 4 1 5 0
0* 6 3 8 4 1 5 2
0 1* 3 8 4 6 5 2
0 1 2* 8 4 6 5 3
0 1 2 3* 4 6 5 8
0 1 2 3 4* 6 5 8
0 1 2 3 4 5* 6 8
0 1 2 3 4 5 6* 8

Selection Sort with Loop

public class SelectionSort {
	public static void main(String[] args) {
		int[] items = { 2, 6, 3, 8, 4, 1, 5, 0 };
		System.out.println("Before Selection Sorting :");
		printArray(items);

		// Perform selection sort
		selectionSort(items);

		System.out.println("After Selection Sorting :");
		printArray(items);
	}

	static void selectionSort(int items[]) {

		// select item one by one based on index
		for (int i = 0; i < items.length - 1; i++) {
			// Find the minimum item in unsorted array
			int min_idx = i;
			for (int j = i + 1; j < items.length; j++)
				if (items[j] < items[min_idx])
					min_idx = j;

			// Swap the found minimum selected item with
			// the first selected item
			int temp = items[min_idx];
			items[min_idx] = items[i];
			items[i] = temp;
		}
	}

	static void printArray(int items[]) {
		for (int item : items) {
			System.out.print(item + " ");
		}
		System.out.println();
	}
}

Output


Before Insertion Sorting :
2 6 3 8 4 1 5 0 
After Insertion Sorting :
0 1 2 3 4 5 6 8 

Insertion Sort Program and Complexity (Big-O)


Insertion sort is a simple sorting algorithm, which consumes one input item for each repetition, and grow a sorted output list. In every iteration, removes one item from input data, find the exact location in the sorted list and inserts it there. This process will repeat as long as no input items remain.

Points to remember

  • Data structure :  Array
  • Worst-case performance : О(n2) comparisons and swaps
  • Best-case performance : O(n) comparisons, O(1) swaps
  • Average performance: О(n2) comparisons and swaps
  • Worst-case space complexity : О(n) total, O(1) auxiliary

See Also: Data Structure and Algorithms Complexity (Big-O)

Advantage

  • Simple Implementation and efficient for small data set.
  • Not change relative order of elements which are already sorted
  • Efficient in comparison to other Quadratic Sort (i.e O(n2)) like Bubble Sort or Selection Sort.
  • Efficient for data set that are already sorted. Time Complexity( i.e O(n)).
  • Only required constant amount of memory space , as size of data set. Space
    Complexity (i.e O(1))

Disadvantage

  • Insertion sort is much less efficient on large lists in compare to algorithms such as quicksort, heapsort, or merge sort.

Insertion Sort Steps

Here * marks the value set on particular iteration.

2 6 3 8 4 1 5 0
2 6* 3 8 4 1 5 0
2 3* 6 8 4 1 5 0
2 3 6 8* 4 1 5 0
2 3 4* 6 8 1 5 0
1* 2 3 4 6 8 5 0
1 2 3 4 5* 6 8 0
0* 1 2 3 4 5 6 8

In following programs you will learn both the ways to implement Insertion Sort by For Loop and Recursion.

Insertion Sort with Loop

public class InsertionSort {
	public static void main(String[] args) {
		int[] items = { 2, 6, 3, 8, 4, 1, 5, 0 };
        System.out.println("Before Sorting :");
        printArrayTR(items);

        //Perform insertion sort
        insertionSort(items);

        System.out.println("After Sorting :");
        printArray(items);
	}

	static void insertionSort(int items[])
    {
        int n = items.length;
        for (int i = 1; i = 0 && items[j] > key) {
            	items[j + 1] = items[j];
                j = j - 1;
            }
            items[j + 1] = key;
            printArrayTR(items);
        }

    }
	static void printArray(int items[])
	{
        for (int item:items)
        {
            System.out.print(item + " ");
        }
        System.out.println();
	}
}

Output


Before Insertion Sorting :
2 6 3 8 4 1 5 0 
After Insertion Sorting :
0 1 2 3 4 5 6 8 

Insertion Sort with Recursion

public class InsertionSortRecursion {
	public static void main(String[] args) {
		int[] items = { 2, 6, 3, 8, 4, 1, 5, 0 };
        System.out.println("Before Insertion Sorting :");
        printArray(items);

        //Perform insertion sort
        insertionSort(items,items.length);

        System.out.println("After Insertion Sorting :");
        printArray(items);
	}

	static void insertionSort(int items[],int n)
	{
		//base case or termination condition
		if(n= 0 && items[j] > last)
        {
        	items[j+1] = items[j];
            j--;
        }
        items[j+1] = last;
	}

	static void printArray(int items[])
	{
        for (int item:items)
        {
            System.out.print(item + " ");
        }
        System.out.println();
	}
}

Output


Before Insertion Sorting :
2 6 3 8 4 1 5 0 
After Insertion Sorting :
0 1 2 3 4 5 6 8 

Linear Search Algorithm,Java Program and Complexity


Linear search also called sequential search is a way for finding a target value within a list. It sequentially checks each element from the list for the target value until a match is found or until all the elements have been searched.

Algorithm

  • Target value search start from the leftmost element of array[] and one by one compare target value with each element of array[]
  • If target value matches with an element, return the index.
  • If target value doesn’t match with any of elements, return -1.

Complexity

  • Best Case Performance O(1)
  • Average Case Performance O(n)
  • Worst Case Performance O(1)

Where O is BiG-O Notation and n is no of element in Array/List.

Java Program for Linear Search of Element

import java.util.Scanner;

class LinearSearch {
	public static void main(String args[]) {
		int c, n, targetValue, array[];

		Scanner in = new Scanner(System.in);
		System.out.println("Enter number of elements");
		n = in.nextInt();
		array = new int[n];

		System.out.println("Enter " + n + " integers");

		for (c = 0; c < n; c++)
			array[c] = in.nextInt();

		System.out.println("Enter target value to find");
		targetValue = in.nextInt();

		for (c = 0; c < n; c++) {
			if (array[c] == targetValue)
			{
				System.out.println(targetValue + " is present at location " + (c + 1) + ".");
				break;
			}
		}
		if (c == n)
			System.out.println(targetValue + " is not present in array.");
	}
}

Output

Enter number of elements
10
Enter 10 integers
2
56
3
7
89
34
78
23
67
13
Enter target value to find
7
7 is present at location 4.

Enter number of elements
7
Enter 7 integers
12
45
34
78
23
87
90
Enter target value to find
32
32 is not present in array.

More

For more DataStructure,Algorithms and Java Programing Test questions and sample code follow below links

Ways to Read Input from Keyboard/User/Console by Java Program


Java Support 4 Ways of  read  input from keyboard:

  • Scanner Class (In java.util package)
  • BufferReader and InputStreamReader (java.io package)
  • DataInputStream (Java.io package)
  • Console Class (Some IDE doesn’t support it For Example : Eclipse)

How Data Accepts from Keyboard ?

For accepting data from keyboard by console we need three objects:

  1. System.in
  2. InputStreamReader
  3. BufferedReader

The data is received in the form of bytes from the keyboard by System.in which is an InputStream object.Then the InputStreamReader reads bytes and decodes them into characters.Then finally BufferedReader object reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

 

InputStreamReader and BufferedReader are classes of java.io package.

Below Java Program showing all four ways of taking user input from console.

 

 

package program.common;

import java.io.BufferedReader;
import java.io.Console;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class UserInputWays {

	public static void main(String[] args) {
		Way1ByScanner();
		System.out.println("=====================================================");
		Way2ByBufferReader();
		System.out.println("=====================================================");
		Way3ByDataStream();
		System.out.println("=====================================================");
		Way4ByConsole();
		System.out.println("=====================================================");
	}

	private static void Way1ByScanner() {
		System.out.println("Way 1 : By Scanner Class");
		Scanner scan = new Scanner(System.in);

		System.out.println("Enter a text string");
		String s = scan.nextLine();
		System.out.println("You entered text string " + s);

		System.out.println("Enter an integer value");
		int a = scan.nextInt();
		System.out.println("You entered integer value " + a);

		System.out.println("Enter a float value");
		float b = scan.nextFloat();
		System.out.println("You entered float value " + b);

	}

	private static void Way2ByBufferReader() {
		System.out.println("Way 2 : By BufferReader and InputStreamReader");
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			System.out.println("Enter a text string");
			String s = br.readLine();
			System.out.println("You entered text string " + s);

			System.out.println("Enter an integer value");
			int a = Integer.parseInt(br.readLine());
			System.out.println("You entered integer value " + a);

			System.out.println("Enter a float value");
			float b = Float.parseFloat(br.readLine());
			System.out.println("You entered float value " + b);

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	private static void Way3ByDataStream() {
		System.out.println("Way 3 : By DataStream");
		try {
			DataInputStream dis = new DataInputStream(System.in);

			System.out.println("Enter a text string");
			String s = dis.readLine();
			System.out.println("You entered text string " + s);

			System.out.println("Enter an integer value");
			int a = dis.readInt();
			System.out.println("You entered integer value " + a);

			System.out.println("Enter a float value");
			float b = dis.readFloat();
			System.out.println("You entered float value " + b);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Eclipse doesn't support Console Class to test that use command prompt
	 */
	private static void Way4ByConsole() {
		System.out.println("Way 4 : By Console Class");
		try
		{
		Console console = System.console();

		System.out.println("Enter a text string");
		String s = console.readLine();
		System.out.println("You entered text string " + s);

		System.out.println("Enter an integer value");
		int a = Integer.parseInt(console.readLine());
		System.out.println("You entered integer value " + a);

		System.out.println("Enter a float value");
		float b = Float.parseFloat(console.readLine());
		System.out.println("You entered float value " + b);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}

}

Output

Way 1 : By Scanner Class
Enter a text string
saurabh Gupta
You entered text string saurabh Gupta
Enter an integer value
35
You entered integer value 35
Enter a float value
80.2
You entered float value 80.2
=====================================================
Way 2 : By BufferReader and InputStreamReader
Enter a text string
Saurabh Gupta
You entered text string Saurabh Gupta
Enter an integer value
35
You entered integer value 35
Enter a float value
80.2
You entered float value 80.2
=====================================================
Way 3 : By DataStream
Enter a text string
Saurabh Gupta
You entered text string Saurabh Gupta
Enter an integer value
35
You entered integer value 859114762
Enter a float value
80.2
You entered float value 4.2004693E-5
=====================================================
Way 4 : By Console Class
Enter a text string
=====================================================
java.lang.NullPointerException
	at program.common.UserInputWays.Way4ByConsole(UserInputWays.java:91)
	at program.common.UserInputWays.main(UserInputWays.java:19)

More

For more Algorithms and Java Programing Test questions and sample code follow below links

Fahrenheit To Celsius Java Program


This program is to convert Fahrenheit to Celsius temperature based on user input value. Below is mathematical formula for conversion from Fahrenheit to Celsius temperature .

T = 9*T/5 + 32 where T is temperature on Celsius scale.

import java.util.Scanner;

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

	    System.out.println("Enter Temperatue in Fahrenheit");
	    temperatue = in.nextInt();

	    temperatue = ((temperatue - 32)*5)/9;

	    System.out.println("Converted Temperatue in Celsius = " + temperatue);
	  }
	}

Outout

Enter Temperatue in Fahrenheit
100
Converted Temperatue in Celsius = 37.77778

Enter Temperatue in Fahrenheit
50
Converted Temperatue in Celsius = 10.0

Enter Temperatue in Fahrenheit
75
Converted Temperatue in Celsius = 23.88889

More

For more Algorithms and Java Programing Test questions and sample code follow below links

 

Floyd Triangle Java Program


This is Java Program to print Floyd triangle of continuous numbers based on inserted users numbers of rows.

import java.util.Scanner;

class FloydTriangle
{
   public static void main(String args[])
   {
      int n, num = 1, c, d;
      Scanner in = new Scanner(System.in);

      System.out.println("Enter the number of rows of floyd's triangle you want");
      n = in.nextInt();

      System.out.println("Floyd's triangle :-");

      for ( c = 1 ; c <= n ; c++ )
      {
         for ( d = 1 ; d <= c ; d++ )
         {
            System.out.print(num+" ");
            num++;
         }

         System.out.println();
      }
   }
}

output

Enter the number of rows of floyd's triangle you want
7
Floyd's triangle :-
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28

More

For more Algorithms and Java Programing Test questions and sample code follow below links

Multiplication Table Java Program


This Java program is for print Multiplication table of Input Number.

import java.util.Scanner;

class MultiplicationTable
{
   public static void main(String args[])
   {
      int n, c;
      System.out.println("Enter an integer value to display it's multiplication table");
      Scanner in = new Scanner(System.in);
      n = in.nextInt();
      System.out.println("Multiplication table of "+n+" is :-");

      for ( c = 1 ; c <= 10 ; c++ )
         System.out.println(n+"*"+c+" = "+(n*c));
   }
}

Output

Enter an integer value to display it's multiplication table

13
Multiplication table of 13 is :-
13*1 = 13
13*2 = 26
13*3 = 39
13*4 = 52
13*5 = 65
13*6 = 78
13*7 = 91
13*8 = 104
13*9 = 117
13*10 = 130

More

For more Algorithms and Java Programing Test questions and sample code follow below links

 

Largest of Three Numbers


This java program is to easily find out largest number in three integers values. But that is not optimize way if numbers are more than that better follow other algorithms.

lass LargestOfThreeNumbers {
	public static void main(String args[]) {
		int x, y, z;

		Scanner in = new Scanner(System.in);
		System.out.println("Please Enter First integer");
		x = in.nextInt();
		System.out.println("Please Enter Second integer");
		y = in.nextInt();
		System.out.println("Please Enter Third integer");
		z = in.nextInt();

		if (x > y && x > z)
			System.out.println("First number is largest.");
		else if (y > x && y > z)
			System.out.println("Second number is largest.");
		else if (z > x && z > y)
			System.out.println("Third number is largest.");
		else
			System.out.println("Entered numbers are not distinct.");
	}
}

Output

Please Enter First integer
10
Please Enter Second integer
20
Please Enter Third integer
5
Second number is largest.

More

For more Algorithms and Java Programing Test questions and sample code follow below links

Palindrome Java Program


Palindrome Definition

“A String is palindrome if it remains unchanged when reversed.”

For Example : String “dad” is a palindrome as reverse of “dad” is “dad” whereas
“program” is not a palindrome. Some other palindrome strings are “nitin”,”mom”, “madam”, “abcba” etc.

Below is simple Java program to check input String is Palindrom or not.

class Palindrome1 {
	public static void main(String args[]) {
		String original, reverse = "";
		Scanner in = new Scanner(System.in);

		System.out.println("Enter a string to check if it is a palindrome");
		original = in.nextLine();

		int length = original.length();

		for (int i = length - 1; i >= 0; i--)
			reverse = reverse + original.charAt(i);

		if (original.equals(reverse))
			System.out.println("Entered string is a palindrome.");
		else
			System.out.println("Entered string is not a palindrome.");

	}
}

Output

Enter a string to check if it is a palindrome
nitin
Entered string is a palindrome.

Enter a string to check if it is a palindrome
Saurabh
Entered string is not a palindrome.

In above program you find out very simple way to check input string is palindrome but in below program you will see to check palindrome string with minimum number of operations because here dividing text in half size and compare with rest of part of String.

import java.util.*;

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

    System.out.println("Enter a string to check if it is a palindrome");
    inputString = in.nextLine();

    int length  = inputString.length();
    int i, begin, end, middle;

    begin  = 0;
    end    = length - 1;
    middle = (begin + end)/2;

    for (i = begin; i <= middle; i++) {
      if (inputString.charAt(begin) == inputString.charAt(end)) {
        begin++;
        end--;
      }
      else {
        break;
      }
    }
    if (i == middle + 1) {
      System.out.println("Entered string is a palindrome.");
    }
    else {
      System.out.println("Entered string is not a palindrome.");
    }
  }
}

Output

Enter a string to check if it is a palindrome
nitin
Entered string is a palindrome.

Enter a string to check if it is a palindrome
Saurabh
Entered string is not a palindrome.

More

For more Algorithms and Java Programing Test questions and sample code follow below links

Prime Numbers Java program


Prime Number Definition

                 “A whole number greater than 1 that is divisible only by itself and 1”.
A prime number will always have factors as 1 and itself. A factor is a whole numbers that can be divided evenly into another number. If Number is having more than two factors are called composite numbers.
The number 1 is neither prime nor a composite Number.
Smallest prime number is 2 and others are in sequence as 2,3,5,7,11,13,17,19,13,29  etc…

Benefit

  • prime numbers are very useful in cryptography.
  • The mathematicians used prime numbers to develop new areas of mathematics, like number theory and knot theory, which developers use today.
This java program prints  number of prime numbers as required from the user.
import java.util.*;

class PrimeNumbers
{
   public static void main(String args[])
   {
      int n, status = 1, num = 3;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter the number of prime numbers you want");
      n = in.nextInt();

      if (n &gt;= 1)
      {
         System.out.println("First "+n+" prime numbers are :-");
         System.out.println(2);
      }

      for ( int count = 2 ; count &lt;=n ;  )
      {
         for ( int j = 2 ; j &lt;= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            count++;
         }
         status = 1;
         num++;
      }
   }
}

Output

Enter the number of prime numbers you want
5
First 5 prime numbers are :-
2
3
5
7
11
Enter the number of prime numbers you want

10
First 10 prime numbers are :-
2
3
5
7
11
13
17
19
23
29

More

For more Algorithms and Java Programing Test questions and sample code follow below links

Odd and Even Java Program


This java program finds if a number is odd or even.

If the number is divisible by 2 then it will be even, otherwise it is odd. We use Java modulus operator to find remainder in our program.

class OddOrEvenNumber{
	public static void main(String args[]) {<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
		int x;
		System.out.println("Enter an integer value to check if it is odd or even ");
		Scanner in = new Scanner(System.in);
		x = in.nextInt();

		if (x % 2 == 0)
			System.out.println("You entered an even number.");
		else
			System.out.println("You entered an odd number.");
	}
}

Output

Enter an integer value to check if it is odd or even
16
You entered an even number.

Enter an integer value to check if it is odd or even
125
You entered an odd number.

More

For more Algorithms and Java Programing Test questions and sample code follow below links

How to Prints Alphabets by Java Loops


Here you will see, How to prints Alphabets through Java all loops (for, While and do while). In these loops we are just increments char value and characters are increment continuously.

public class PrintAlphabets {

	public static void main(String[] args) {
		// By for Loop
		char ch;
		for (ch = 'a'; ch <= 'z'; ch++) {
			System.out.print(ch + " ");
		}
		System.out.println();

		// By While loop
		char c = 'a';

		while (c <= 'z') {
			System.out.print(c + " ");
			c++;
		}
		System.out.println();

		// By do while loop
		c = 'A';

		do {
			System.out.print(c + " ");
			c++;
		} while (c <= 'Z');
	}

}

Output

a b c d e f g h i j k l m n o p q r s t u v w x y z
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

More

For more Algorithms and Java Programing Test questions and sample code follow below links

 

Frequently Asked Algorithms and Programs in Interviews


Below are most frequently asked algorithms and programs in interview to test interviewee programming and logical skill. These question can be asked with fresher and any senior level also in IT.

How to Swap two Numbers with and with out temporary variable.


Here I will show you how you can swap two numbers A=20 and B=10 with and without temporary variables as A=10 and B=20.

Swap Numbers with Temporary Variable

I will take one more temporary variable as temp to keep value of B so that during  copy of value A to B value of B is in temp and now we can copy value of temp to A. As below

temp=B       (This state : A=20, B=10, temp=10)

B=A;            (This state : A=20, B=20, temp=10)

A=temp      (This state : A=10, B=20, temp=10)

By applying above logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Swap Numbers without Temporary Variable

There are two ways two swap two numbers without using any temporary variable.

Addition and Subtraction

Here you will see how to swap numbers A=20 and B=10 by using addition and subtraction operations.

A=A+B           (This state : A=30, B=10)

B=A-B           (This state : A=30, B=20)

A=A-B           (This state : A=10, B=20)

By applying above addition and subtraction logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Multiplication and Division

Here you will see how to swap numbers A=20 and B=10 by using multiplication and division operations.

A=A*B           (This state : A=200, B=10)

B=A/B           (This state : A=200, B=20)

A=A/B           (This state : A=10, B=20)

By applying above multiplication and division logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Swap Numbers Java Program

package test;

import java.util.Scanner;

public class SwapNumbers {

	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		System.out.println("Please Enter First Number");
		int A=scan.nextInt();

		System.out.println("Please Enter Second Number");
		int B=scan.nextInt();

		//swap Numbers with temporary variable
		swapNumbersWithTemp(A,B);
		//swap Numbers without temporary variable : Add and Sub
		swapNumbersWithoutTempAddSub(A,B);
		//swap Numbers without temporary variable : Mul and Div
		swapNumbersWithoutTempMulDiv(A,B);
	}

	private static void swapNumbersWithTemp(int A, int B)
	{
		int temp=B;
		B=A;
		A=temp;

		System.out.println("Numbers after swap with temporary variables");
		System.out.println("A="+A+"and B="+B);
	}

	private static void swapNumbersWithoutTempAddSub(int A, int B)
	{
		A=A+B;
		B=A-B;
		A=A-B;

		System.out.println("Numbers after swap without temporary variables: Add and Sub operation");
		System.out.println("A="+A+"and B="+B);
	}

	private static void swapNumbersWithoutTempMulDiv(int A, int B)
	{
		A=A*B;
		B=A/B;
		A=A/B;

		System.out.println("Numbers after swap without temporary variables: MUl and Div operation");
		System.out.println("A="+A+"and B="+B);
	}

}

Output

Please Enter First Number
20
Please Enter Second Number
10
Numbers after swap with temporary variables
A=10and B=20
Numbers after swap without temporary variables: Add and Sub operation
A=10and B=20
Numbers after swap without temporary variables: MUl and Div operation
A=10and B=20
<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span><span 			

 

 

More Info

For more Algorithms and Java Programing Test questions and sample code follow below links

 

Binary Search Java Program


Binary search, also known as half-interval search,binary chop or logarithmic search.

How it Works?

Binary search works on sorted arrays values. Binary search begins by comparing the middle element of the array with the target value. If the target value matches the middle element, its position in the array is returned. If the target value is less than or greater
than the middle element, the search continues in the lower or upper half of the array, respectively, eliminating the other half from consideration.If the search ends with the remaining half being empty, the target is not in the array.

Time and Space Complexity?

Binary search runs in at worst logarithmic time, making O(log n) comparisons and takes constant (O(1)) space.

where n is the number of elements in the array, the O is Big O notation, and log is the logarithm.

Java API  for Binary Search

Java Arrays class also provide api’s for Binary Search. You can use as below

import java.util.Arrays;

public class BinarySearchByJavaAPI {

	public static void main(String[] args) {
		char characters[] = { 'l', 'm', 'n', 'p', 'q<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>' };

	    System.out.println(Arrays.binarySearch(characters, 'a'));
	    System.out.println(Arrays.binarySearch(characters, 'p'));

	}

}

Java Program for Binary Search

import java.util.Scanner;

class BinarySearch
{
  public static void main(String args[])
  {
    int c, first, last, middle, n, search, array[];

    Scanner in = new Scanner(System.in);
    System.out.println("Enter number of elements");
    n = in.nextInt();
    array = new int[n];

    System.out.println("Enter " + n + " sorted integers");

    for (c = 0; c < n; c++)
      array[c] = in.nextInt();

    System.out.println("Enter value to find");
    search = in.nextInt();

    first  = 0;
    last   = n - 1;
    middle = (first + last)/2;

    while( first <= last )
    {
      if ( array[middle] < search )                 first = middle + 1;                else if ( array[middle] == search )     {                System.out.println(search + " found at location " + (middle + 1) + ".");                break;        }        else                last = middle - 1;           middle = (first + last)/2;     }     if ( first ><span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span> last )
      System.out.println(search + " is not present in the list.\n");
  }
}

More Info

For more Algorithms and Java Programing Test questions and sample code follow below links