Selection Sort In Java
IntroductionIn this example we are going to sort the values of an array using selection sort.
In selection sorting algorithm, find the minimum value in the array then swap it first position. In next step leave the first value and find the minimum value within remaining values. Then swap it with the value of minimum index position. Sort the remaining values by using same steps. Selection sort is probably the most intuitive sorting algorithm to invent.
The complexity of selection sort algorithm is in worst-case, average-case, and best-case run-time of Θ(n2), assuming that comparisons can be done in constant time.
Code description:
In selection sort algorithm to find the minimum value in the array. First assign minimum index in key (index_of_min=x). Then find the minimum value and assign the index of minimum value in key (index_of_min=y). Then swap the minimum value with the value of minimum index.
At next iteration leave the value of minimum index position and sort the remaining values by following same steps.
Working of the selection sort :
Say we have an array unsorted A[0],A[1],A[2]................ A[n-1] and A[n] as input. Then the following steps are followed by selection sort algorithm to sort the values of an array . (Say we have a key index_of_min that indicate the position of minimum value)
1.Initaily varaible index_of_min=0;
2.Find the minimum value in the unsorted array.
3.Assign the index of the minimum value into index_of_min variable.
4.Swap minimum value to first position.
5.Sort the remaining values of array (excluding the first value).
The code of the program :
public class selectionSort{ public static void main(String a[]){ int i; int array[] = { 12 , 9 , 4 , 99 , 120 , 1 , 3 , 10 }; System.out.println( "\n\n RoseIndia\n\n" ); System.out.println( " Selection Sort\n\n" ); System.out.println( "Values Before the sort:\n" ); for (i = 0 ; i < array.length; i++) System.out.print( array[i]+ " " ); System.out.println(); selection_srt(array, array.length); System.out.print( "Values after the sort:\n" ); for (i = 0 ; i <array.length; i++) System.out.print(array[i]+ " " ); System.out.println(); System.out.println( "PAUSE" ); } public static void selection_srt( int array[], int n){ for ( int x= 0 ; x<n; x++){ int index_of_min = x; for ( int y=x; y<n; y++){ if (array[index_of_min]<array[y]){ index_of_min = y; } } int temp = array[x]; array[x] = array[index_of_min]; array[index_of_min] = temp; } } } |
C:\array\sorting>javac selectionSort.java
C:\array\sorting>java selectionSort
RoseIndia
Selection Sort
Values Before the sort:
12 9 4 99 120 1 3 10
Values after the sort:
120 99 12 10 9 4 3 1
PAUSE
C:\array\sorting>_
|
Insertion Sort In Java
IntroductionIn this example we are going to sort integer values of an array using insertion sort.
Insertion sorting algorithm is similar to bubble sort. But insertion sort is more efficient than bubble sort because in insertion sort the elements comparisons are less as compare to bubble sort. In insertion sorting algorithm compare the value until all the prior elements are lesser than compared value is not found. This mean that the all previous values are lesser than compared value. This algorithm is more efficient than the bubble sort .Insertion sort is a good choice for small values and for nearly-sorted values. There are more efficient algorithms such as quick sort, heap sort, or merge sort for large values .
Positive feature of insertion sorting:
1.It is simple to implement
2.It is efficient on (quite) small data values
3.It is efficient on data sets which are already nearly sorted.
The complexity of insertion sorting is O(n) at best case of an already sorted array and O(n2) at worst case .
Code description:
In insertion sorting take the element form left assign value into a variable. Then compare the value with previous values. Put value so that values must be lesser than the previous values. Then assign next value to a variable and follow the same steps relatively until the comparison not reached to end of array.
Working of insertion sorting:
The code of the program :
public class InsertionSort{ public static void main(String a[]){ int i; int array[] = { 12 , 9 , 4 , 99 , 120 , 1 , 3 , 10 }; System.out.println( "\n\n RoseIndia\n\n" ); System.out.println( " Selection Sort\n\n" ); System.out.println( "Values Before the sort:\n" ); for (i = 0 ; i < array.length; i++) System.out.print( array[i]+ " " ); System.out.println(); insertion_srt(array, array.length); System.out.print( "Values after the sort:\n" ); for (i = 0 ; i <array.length; i++) System.out.print(array[i]+ " " ); System.out.println(); System.out.println( "PAUSE" ); } public static void insertion_srt( int array[], int n){ for ( int i = 1 ; i < n; i++){ int j = i; int B = array[i]; while ((j > 0 ) && (array[j- 1 ] > B)){ array[j] = array[j- 1 ]; j--; } array[j] = B; } } } |
C:\array\sorting>javac InsertionSort.java
C:\array\sorting>java InsertionSort
RoseIndia
Selection Sort
Values Before the sort:
12 9 4 99 120 1 3 10
Values after the sort:
1 3 4 9 10 12 99 120
PAUSE
C:\array\sorting>_
|
Quick Sort in Java
In this example we are going to sort integer values of an array using quick sort.
Quick sort algorithm is developed by C. A. R. Hoare. Quick sort is a comparison sort. The working of quick sort algorithm is depending on a divide-and-conquer strategy. A divide and conquer strategy is dividing an array into two sub-arrays. Quick sort is one of the fastest and simplest sorting algorithm. The complexity of quick sort in the average case is Θ(n log(n)) and in the worst case is Θ(n2).
Code description:
In quick sort algorithm pick an element from array of elements. This element is called the pivot. Then compare the the values from left to right until a greater element is find then swap the values. Again start comparison from right with pivot. When lesser element is find then swap the values. Follow the same steps until all elements which are less than the pivot come before the pivot and all elements greater than the pivot come after it. After this partitioning, the pivot is in its last position. This is called the partition operation. Recursively sort the sub-array of lesser elements and the sub-array of greater elements.
Working of quick sort algorithm:
Input:12 9 4 99 120 1 3 10 13
Output:1 3 4 10 12 13 99 120
The code of the program :
public class QuickSort{ public static void main(String a[]){ int i; int array[] = { 12 , 9 , 4 , 99 , 120 , 1 , 3 , 10 , 13 }; System.out.println( "\n\n RoseIndia\n\n" ); System.out.println( " Quick Sort\n\n" ); System.out.println( "Values Before the sort:\n" ); for (i = 0 ; i < array.length; i++) System.out.print( array[i]+ " " ); System.out.println(); quick_srt(array, 0 ,array.length- 1 ); System.out.print( "Values after the sort:\n" ); for (i = 0 ; i <array.length; i++) System.out.print(array[i]+ " " ); System.out.println(); System.out.println( "PAUSE" ); } public static void quick_srt( int array[],int low, int n){ int lo = low; int hi = n; if (lo >= n) { return ; } int mid = array[(lo + hi) / 2 ]; while (lo < hi) { while (lo<hi && array[lo] < mid) { lo++; } while (lo<hi && array[hi] > mid) { hi--; } if (lo < hi) { int T = array[lo]; array[lo] = array[hi]; array[hi] = T; } } if (hi < lo) { int T = hi; hi = lo; lo = T; } quick_srt(array, low, lo); quick_srt(array, lo == low ? lo+ 1 : lo, n); } } |
C:\array\sorting>javac QuickSort.java
C:\array\sorting>java QuickSort
RoseIndia
Quick Sort
Values Before the sort:
12 9 4 99 120 1 3 10 13
Values after the sort:
1 3 4 9 10 12 13 99 120
PAUSE
C:\array\sorting>_
|
Merge Sort in Java
IntroductionIn this example we are going to sort integer values of an array using merge sort.
In merge sorting algorithm unsorted values are divided into two equal parts iteratively. Then merge both parts and sort it. Then again merge the next part and sort it. Do it iteratively until the values are not in sorted order. In merge sorting the number of elements must be even. The merge sorting is invented by John von Neumann in 1945 .
The complexity of the merge sorting is in worst-case O(n log n) and in average case O(n log n).
Code description:
In merge sort split the array values in halves recursively until each half has only single element. Merge the two 1/2 values together and sort the values. Do same steps iteratively until the values are not sorted.
Working of merge sort algorithm:
Say we have an array unsorted A[0],A[1],A[2]................ A[n-1] and A[n] as input. Then the following steps are followed by merge sort algorithm to sort the values of an array.
Step1:Spliting the values of array
Divide the values into two equal 1/2
A[0],A[1],A[2].........A[n/2-1] & A[n/2]....... .................A[n-1], A[n]
Again divide two equal 1/2
A[0] a[1]A[2]..............A[(n/2-1)/2-1] & A[(n/2-1)/2]............A[n/2-1],
A[n/2].............A[(2n-1)/2-1] & a[(2n-1)/2].............A[n-1],A[n]
..........................................................................................................................
..........................................................................................................................
........................................................................................................................
A[0] & A[1] & A[2]& A[3],..............................................................A[n-1]& A[n]
Step2:Merge two values and sort the values
A[0],A[1] & A[2],A[3]&..................................................................&A[n-1],A[n]
If A[1]<A[0],A[]<A[3]........................................................................A[n-1]>A[n]
then
A[1]A[0],A[2]A[3],...............................................................................A[n]A[n-1]
Step3:Merge four values and sort the values
A[2] A[1] A[0] A[3],...................................................................................A[n-1]
..................................................................................................................
..................................................................................................................
.................................................................................................................
Step3:Merge n values and sort the values
A[2]A[6]......................................................................................................A[n-5]
Where n must be even number.
Steps of Merge Sort:
Say unsorted an array values are:
12,9,4,99,120,1,3,10
The code of the program :
public class mergeSort{ public static void main(String a[]){ int i; int array[] = { 12 , 9 , 4 , 99 , 120 , 1 , 3 , 10 }; System.out.println( "\n\n RoseIndia\n\n" ); System.out.println( " Selection Sort\n\n" ); System.out.println( "Values Before the sort:\n" ); for (i = 0 ; i < array.length; i++) System.out.print( array[i]+ " " ); System.out.println(); mergeSort_srt(array, 0 , array.length- 1 ); System.out.print( "Values after the sort:\n" ); for (i = 0 ; i <array.length; i++) System.out.print(array[i]+ " " ); System.out.println(); System.out.println( "PAUSE" ); } public static void mergeSort_srt( int array[],int lo, int n){ int low = lo; int high = n; if (low >= high) { return ; } int middle = (low + high) / 2 ; mergeSort_srt(array, low, middle); mergeSort_srt(array, middle + 1 , high); int end_low = middle; int start_high = middle + 1 ; while ((lo <= end_low) && (start_high <= high)) { if (array[low] < array[start_high]) { low++; } else { int Temp = array[start_high]; for ( int k = start_high- 1 ; k >= low; k--) { array[k+ 1 ] = array[k]; } array[low] = Temp; low++; end_low++; start_high++; } } } } |
C:\array\sorting>javac mergeSort.java
C:\array\sorting>java mergeSort
RoseIndia
Selection Sort
Values Before the sort:
12 9 4 99 120 1 3 10
Values after the sort:
1 3 4 9 10 12 99 120
PAUSE
C:\array\sorting>_
|
Linear
Search in Java
In this section, we are going to
find an element from an array using Linear Searching. Linear searching is a
good way to find an element from the array. The array can be of any order, it
checks whether a certain element (number , string , etc. ) is in a specified
array or not. Basically it is used for small arrays. In the given code, we have
allowed the user to enter the numbers to be stored into the arrays. If the
element is found we can return the index where the element is located in the
array. If the element is not found we can return -1.
Here is the code:
import
java.util.*;
public class LinearSearch {
public int find(final int[] data, final int key) {
for (int i = 0; i < data.length; ++i) {
if (data[i] > key)
return -1;
else if (data[i] == key)
return i;
}
return -1;
}
public static void main(String[] args) {
final int arr[] = new int[10];
System.out.println("Enter 10 numbers");
Scanner input = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
}
LinearSearch search = new LinearSearch();
System.out.print("Enter the element to search: ");
int num=input.nextInt();
int n = search.find(arr, num);
if ((n >= 0) && (n < arr.length)) {
System.out.println("Found at index: " + n);
} else {
System.out.println("Not Found");
}
}
}
public class LinearSearch {
public int find(final int[] data, final int key) {
for (int i = 0; i < data.length; ++i) {
if (data[i] > key)
return -1;
else if (data[i] == key)
return i;
}
return -1;
}
public static void main(String[] args) {
final int arr[] = new int[10];
System.out.println("Enter 10 numbers");
Scanner input = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
}
LinearSearch search = new LinearSearch();
System.out.print("Enter the element to search: ");
int num=input.nextInt();
int n = search.find(arr, num);
if ((n >= 0) && (n < arr.length)) {
System.out.println("Found at index: " + n);
} else {
System.out.println("Not Found");
}
}
}
Output:
Enter
10 numbers:
1
2
3
4
5
6
7
8
9
10
Enter
the element to search:5
Found
at index: 4
Binary
Search in Java
In this section, we are going to
search an element from an array using Binary Search. The advantage of a binary
search over a linear search is astounding for large numbers. It can be done
either recursively or iteratively. In the given code, we have allowed the user
to enter the numbers to be stored into the array.Then we start the search from
the middle element of the array. If the middle element is equal to the searched
value, the algorithm stops otherwise we have two cases:
1)If searched value is less than the
middle element. In this case, again get the middle element of the first half of
the specified array.
2)If searched value is greater, than the middle element. In this case, again get the middle element of the second half of the specified array.
This will continue until we get the searched element.
2)If searched value is greater, than the middle element. In this case, again get the middle element of the second half of the specified array.
This will continue until we get the searched element.
Here is the code:
import
java.util.*;
public class BinarySearch {
public static void main(String[] args) {
int[] intArray = new int[10];
int searchValue = 0, index;
System.out.println("Enter 10 numbers");
Scanner input = new Scanner(System.in);
for (int i = 0; i < intArray.length; i++) {
intArray[i] = input.nextInt();
}
System.out.print("Enter a number to search for: ");
searchValue = input.nextInt();
index = binarySearch(intArray, searchValue);
if (index != -1) {
System.out.println("Found at index: " + index);
} else {
System.out.println("Not Found");
}
}
static int binarySearch(int[] search, int find) {
int start, end, midPt;
start = 0;
end = search.length - 1;
while (start <= end) {
midPt = (start + end) / 2;
if (search[midPt] == find) {
return midPt;
} else if (search[midPt] < find) {
start = midPt + 1;
} else {
end = midPt - 1;
}
}
return -1;
}
}
public class BinarySearch {
public static void main(String[] args) {
int[] intArray = new int[10];
int searchValue = 0, index;
System.out.println("Enter 10 numbers");
Scanner input = new Scanner(System.in);
for (int i = 0; i < intArray.length; i++) {
intArray[i] = input.nextInt();
}
System.out.print("Enter a number to search for: ");
searchValue = input.nextInt();
index = binarySearch(intArray, searchValue);
if (index != -1) {
System.out.println("Found at index: " + index);
} else {
System.out.println("Not Found");
}
}
static int binarySearch(int[] search, int find) {
int start, end, midPt;
start = 0;
end = search.length - 1;
while (start <= end) {
midPt = (start + end) / 2;
if (search[midPt] == find) {
return midPt;
} else if (search[midPt] < find) {
start = midPt + 1;
} else {
end = midPt - 1;
}
}
return -1;
}
}
Output
Enter
10 numbers:
1
2
3
4
5
6
7
8
9
10
Enter
a number to search for:5
Found
at index: 4
Implementing a Stack in Java
In this section, you will learn how to implement a stack in Java. A Stack is like a bucket in which you can put elements one-by-one in sequence and retrieve elements from the bucket according to the sequence of the last entered element. Stack is a collection of data and follows the LIFO (Last in, first out) rule that mean you can insert the elements one-by-one in sequence and the last inserted element can be retrieved at once from the bucket. Elements are inserted and retrieved to/from the stack through the push() and pop() method.This program implements a stack and follows the LIFO rule. It asks you for the number of elements which have to be entered in the stack and then it takes elements for insertion in the stack. All the elements present in the stack are shown from the last inserted element to the first inserted element.
Stack<Integer>():
Above constructor of the Stack class creates a empty stack which holds the integer type value which is mention with the creation of stack. The Stack class extends the Vector class and both classes are implemented from the java.util.*; package.
Stack.push(Object obj):
Above method is used to insert or push the data or element in the stack. It takes an object like: data or elements and push its onto the top of the stack.
Stack.pop():
This is the method to removes the objects like: data or elements at the top positions of stack.
Here is the code of program:
import java.io.*; import java.util.*; public class StackImplement{ Stack<Integer> stack; String str; int num, n; public static void main(String[] args){ StackImplement q = new StackImplement(); } public StackImplement(){ try { stack = new Stack<Integer>(); InputStreamReader ir = new InputStreamReader(System.in); BufferedReader bf = new BufferedReader(ir); System.out.print( "Enter number of elements : " ); str = bf.readLine(); num = Integer.parseInt(str); for ( int i = 1 ; i <= num; i++){ System.out.print( "Enter elements : " ); str = bf.readLine(); n = Integer.parseInt(str); stack.push(n); } } catch (IOException e){} System.out.print( "Retrieved elements from the stack : " ); while (!stack.empty()){ System.out.print(stack.pop() + " " ); } } } |
Implement the Queue in Java
In this section, you will learn how to implement the queue. A queue holds a collection of data or elements and follows the FIFO ( First In First Out) rule. The FIFO that means which data added first in the list, only that element can be removed or retrieved first from the list. In other sense, You can remove or perform operation on that data which had been added first in the Collection (list). Whenever you need to remove the last added element then you must remove all these elements which are entered before the certain element.The given program implements a queue. It takes all elements as input by user. These values are added to the list and shows first, last and the rest elements present in the list separately. Some methods and APIs are explained below which have been used in the program for the certain purposes:
LinkedList<Integer>():
This is the constructor of the LinkedList class. This class is used by importing the java.util.*; package. This constructor is used for constructing an empty list. It can contain integer types data in the given program because in the declaration of the LinkedList class type checking has been used. This is an implementation of the List interface of the Collections Framework. The LinkeedList class provides inserting and deleting the data to/from the list.
removeFirst():
Above method removes and returns the first element of the list.
removeLast():
Above method removes and returns the last element of the list.
list.isEmpty():
This method checks whether the list is empty or not.
remove():
This method used to remove the elements in the list in a specified sequence.
Here is the code of program:
import java.io.*; import java.util.*; public class QueueImplement{ LinkedList<Integer> list; String str; int num; public static void main(String[] args){ QueueImplement q = new QueueImplement(); } public QueueImplement(){ try { list = new LinkedList<Integer>(); InputStreamReader ir = new InputStreamReader(System.in); BufferedReader bf = new BufferedReader(ir); System.out.println( "Enter number of elements : " ); str = bf.readLine(); if ((num = Integer.parseInt(str)) == 0 ){ System.out.println( "You have entered either zero/null." ); System.exit( 0 ); } else { System.out.println( "Enter elements : " ); for ( int i = 0 ; i < num; i++){ str = bf.readLine(); int n = Integer.parseInt(str); list.add(n); } } System.out.println( "First element :" + list.removeFirst()); System.out.println( "Last element :" + list.removeLast()); System.out.println( "Rest elements in the list :" ); while (!list.isEmpty()){ System.out.print(list.remove() + "\t" ); } } catch (IOException e){ System.out.println(e.getMessage() + " is not a legal entry." ); System.exit( 0 ); } } } |
Download
this example
Circular Queue:
import
java.util.AbstractCollection;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
public final class CircularQueue extends AbstractCollection {
// This is the largest capacity allowed by this implementation
private static final int MAX_CAPACITY = 1 << 30;
private static final int DEFAULT_CAPACITY = 1 << 8;
private int size = 0;
private int producerIndex = 0;
private int consumerIndex = 0;
// capacity must be a power of 2 at all times
private int capacity;
private int maxCapacity;
// we mask with capacity -1. This variable caches that values
private int bitmask;
private Object[] q;
public CircularQueue() {
this(DEFAULT_CAPACITY);
}
// Construct a queue which has at least the specified capacity. If
// the value specified is a power of two then the queue will be
// exactly the specified size. Otherwise the queue will be the
// first power of two which is greater than the specified value.
public CircularQueue(int c) {
this(c, MAX_CAPACITY);
}
public CircularQueue(int c, int mc) {
if (c > mc) {
throw new IllegalArgumentException("Capacity greater than maximum");
}
if (mc > MAX_CAPACITY) {
throw new IllegalArgumentException("Maximum capacity greater than " +
"allowed");
}
for (capacity = 1; capacity < c; capacity <<= 1) ;
for (maxCapacity = 1; maxCapacity < mc; maxCapacity <<= 1) ;
bitmask = capacity - 1;
q = new Object[capacity];
}
// Constructor used by clone()
private CircularQueue(CircularQueue oldQueue) {
size = oldQueue.size;
producerIndex = oldQueue.producerIndex;
consumerIndex = oldQueue.consumerIndex;
capacity = oldQueue.capacity;
maxCapacity = oldQueue.maxCapacity;
bitmask = oldQueue.bitmask;
q = new Object[oldQueue.q.length];
System.arraycopy(oldQueue.q, 0, q, 0, q.length);
}
private boolean expandQueue() {
// double the size of the queue
// This design assumes that this is a rare case
if (capacity == maxCapacity) {
return false;
}
int old_capacity = capacity;
Object[] old_q = q;
capacity += capacity;
bitmask = capacity - 1;
q = new Object[capacity];
System.arraycopy(old_q, consumerIndex, q, 0, old_capacity - consumerIndex);
if (consumerIndex != 0) {
System.arraycopy(old_q, 0, q, old_capacity - consumerIndex,
consumerIndex);
}
consumerIndex = 0;
producerIndex = size;
return true;
}
public boolean add(Object obj) {
if (size == capacity) {
// no room
if (!expandQueue()) return false;
}
size++;
q[producerIndex] = obj;
producerIndex = (producerIndex + 1) & bitmask;
return true;
}
public Object remove() {
Object obj;
if (size == 0) return null;
size--;
obj = q[consumerIndex];
q[consumerIndex] = null; // allow gc to collect
consumerIndex = (consumerIndex + 1) & bitmask;
return obj;
}
public boolean isEmpty() { return size == 0; }
public int size() { return size; }
public int capacity() { return capacity; }
public Object peek() {
if (size == 0) return null;
return q[consumerIndex];
}
public void clear() {
Arrays.fill(q, null);
size = 0;
producerIndex = 0;
consumerIndex = 0;
}
public Object clone() {
return new CircularQueue(this);
}
public String toString() {
StringBuffer s = new StringBuffer(super.toString() + " - capacity: '" +
capacity() + "' size: '" + size() + "'");
if (size > 0) {
s.append(" elements:");
for (int i = 0; i < size; ++i) {
s.append('\n');
s.append('\t');
s.append(q[consumerIndex + i & bitmask].toString());
}
}
return s.toString();
}
public Iterator iterator() {
return new Iterator() {
private final int ci = consumerIndex;
private final int pi = producerIndex;
private int s = size;
private int i = ci;
public boolean hasNext() {
checkForModification();
return s > 0;
}
public Object next() {
checkForModification();
if (s == 0) throw new NoSuchElementException();
s--;
Object r = q[i];
i = (i + 1) & bitmask;
return r;
}
public void remove() {
throw new UnsupportedOperationException();
}
private void checkForModification() {
if (ci != consumerIndex) throw new ConcurrentModificationException();
if (pi != producerIndex) throw new ConcurrentModificationException();
}
};
}
}
Dequeue:
import java.lang.reflect.Array;
class Deque<Item>
{
private int maxSize=100;
private final Item[] array;
private int front,rear;
private int numberOfItems;
public Deque()
{
array=(Item[])(new Object[maxSize]);
front=0;
rear=-1;
numberOfItems=0;
}
public boolean isEmpty()
{
return (numberOfItems==0);
}
public void addFirst(Item item)
{
if(front==0)
front=maxSize;
array[--front]=item;
numberOfItems++;
}
public void addLast(Item item)
{
if(rear==maxSize-1)
rear=-1;
array[++rear]=item;
numberOfItems++;
}
public Item removeFirst()
{
Item temp=array[front++];
if(front==maxSize)
front=0;
numberOfItems--;
return temp;
}
public Item removeLast()
{
Item temp=array[rear--];
if(rear==-1)
rear=maxSize-1;
numberOfItems--;
return temp;
}
public int getFirst()
{
return front;
}
public int getLast()
{
return rear;
}
public static void main(String[] args)
{
Deque<String> element1=new Deque<String>();
Deque<String> element2=new Deque<String>();
for(int i=0;i<args.length;i++)
element1.addFirst(args[i]);
try {
for(;element1.numberOfItems+1>0;)
{
String temp=element1.removeFirst();
System.out.println(temp);
}
}
catch(Exception ex)
{
System.out.println("End Of Execution due to remove from empty queue");
}
System.out.println();
for(int i=0;i<args.length;i++)
element2.addLast(args[i]);
try {
for(;element2.numberOfItems+1>0;)
{
String temp=element2.removeLast();
System.out.println(temp);
}
}
catch(Exception ex)
{
System.out.println("End Of Execution due to remove from empty queue");
}
}
}Priority Queue:
/**
* This class implements a priority queue that fits into
* the Java 1.2 Collection hierarchy. This is a min-based
* priority queue though a max-based queue can be easily obtained
* by supplying an alternative <code>Comparator</code> object when
* the priority queue is constructed.
* <P>
* This implementation
* supports O(log n) operations for all fundamental priority
* queue operations: add and peek/remove;
* the implementation uses a standard min-heap. There is no
* restriction on inserting unique elements, so it is ok to insert
* an element that is equal to an element already in the priority
* queue. No guarantees are provided about which of two equal elements
* is returned first by a peek/remove.
* <P>
* The elements in a priority queue must implement the
* <code>Comparable</code> interface or else a
* <code>Comparator</code> must be provided when the priority queue is
* constructed.
* <P>
* For version 2.0: the methods have been renamed to be consistent
* with the Queue interface and PriorityQueue implementation from
* Java 5. This class should be drop-in/compatible with the Java
* 5 priority queue except this class doesn't support generics. In
* addition, this class does not implement methods <code>poll</code>
* or <code>offer</code> from the Java 5 Queue interface. Instead,
* it provides <code>add</code> and <code>remove</code>.
* <P>
* @author Owen Astrachan
* @version 1.0, July 2000
* @version 2.0, October 2004
*
*/
import java.util.*;
public class PriorityQueue extends AbstractCollection
{
private static class DefaultComparator implements Comparator
{
public int compare (Object o1, Object o2)
{
return ((Comparable) o1).compareTo(o2);
}
}
private Comparator myComp = new DefaultComparator();
private int mySize;
private ArrayList myList;
/**
* This is a trivial iterator class that returns
* elements in the PriorityQueue ArrayList field
* one-at-a-time
*/
private class PQItr implements Iterator
{
public Object next()
{
return myList.get(myCursor);
}
public boolean hasNext()
{
return myCursor <= mySize;
}
public void remove()
{
throw new UnsupportedOperationException("remove not implemented");
}
private int myCursor = 1;
}
/**
* constructs an empty priority queue, when new elements
* are added their natural order will be used to determine
* which is minimal. This means elements that are added must
* implement the <code>Comparable</code> interface and must
* be <em>mutually comparable</em>, i.e.,
* <code>e1.compareTo(e2)</code> must not throw a
* <code>CastCastException</code> for any two elements <code>e1</code>
* and <code>e2</code> in the priority queue.
*/
public PriorityQueue()
{
myList = new ArrayList(32);
myList.add(null); // first slot has index 1
mySize = 0;
}
/**
* constructs an empty priority queue, when new elements
* are added the <code>Comparator comp</code> determines which is
* smaller.
*
* @param comp is the <code>Comparator</code> used in determining order
*/
public PriorityQueue(Comparator comp)
{
this();
myComp = comp;
}
/**
* all elements in coll are added to the priority queue. The
* complexity is O(n) where <code>coll.size() == n</code>
*
* @param coll is a collection of mutually comparable elements
*/
public PriorityQueue(Collection coll)
{
this();
myList.addAll(coll);
mySize = coll.size();
for(int k=coll.size()/2; k >= 1; k--)
{
heapify(k);
}
}
/**
* A new element <code>o</code> is added to the priority queue
* in O(log n) time where n is the size of the priority queue.
* <P>
* The return value should be ignored, a boolean value must be
* returned because of the requirements of the
* <code>Collection</code> interface.
*
* @param o is the (Comparable) object added to the priority queue
* @return true
*/
public boolean add(Object o)
{
myList.add(o); // stored, but not correct location
mySize++; // added element, update count
int k = mySize; // location of new element
while (k > 1 && myComp.compare(myList.get(k/2), o) > 0)
{
myList.set(k, myList.get(k/2));
k /= 2;
}
myList.set(k,o);
return true;
}
/**
* @return the number of elements in the priority queue
*/
public int size()
{
return mySize;
}
/**
* @return true if and only if the priority queue is empty
*/
public boolean isEmpty()
{
return mySize == 0;
}
/**
* The smallest/minimal element is removed and returned
* in O(log n) time where n is the size of the priority queue.
*
* @return the smallest element (and removes it)
*/
public Object remove()
{
if (! isEmpty())
{
Object hold = myList.get(1);
myList.set(1, myList.get(mySize)); // move last to top
myList.remove(mySize); // pop last off
mySize--;
if (mySize > 1)
{
heapify(1);
}
return hold;
}
return null;
}
/**
* Executes in O(1) time, returns smallest element
* @return the minimal element in the priority queue
*/
public Object peek()
{
return myList.get(1);
}
/**
* The order of the elements returned by the iterator is not specified
* @return an iterator of all elements in priority queue
*/
public Iterator iterator()
{
return new PQItr();
}
/**
* works in O(log(size()-vroot)) time
* @param vroot is the index at which re-heaping occurs
* @precondition: subheaps of index vroot are heaps
* @postcondition: heap rooted at index vroot is a heap
*/
private void heapify(int vroot)
{
Object last = myList.get(vroot);
int child, k = vroot;
while (2*k <= mySize)
{
child = 2*k;
if (child < mySize &&
myComp.compare(myList.get(child),
myList.get(child+1)) > 0)
{
child++;
}
if (myComp.compare(last, myList.get(child)) <= 0)
{
break;
}
else
{
myList.set(k, myList.get(child));
k = child;
}
}
myList.set(k, last);
}
/**
* simple test harnass that inserts all arguments into a
* priority queue and then removes them one at a time and prints
* them one per line as they are removed
* thus effectively sorting in O(n log n) time
*/
public static void main(String args[])
{
PriorityQueue pq = new PriorityQueue(Arrays.asList(args));
while (pq.size() > 0)
{
System.out.println(pq.peek());
pq.remove();
}
}
}
Converts infix arithmetic expressions to postfix :
import java.io.IOException; public class InToPost { private Stack theStack; private String input; private String output = ""; public InToPost(String in) { input = in; int stackSize = input.length(); theStack = new Stack(stackSize); } public String doTrans() { for (int j = 0; j < input.length(); j++) { char ch = input.charAt(j); switch (ch) { case '+': case '-': gotOper(ch, 1); break; // (precedence 1) case '*': // it's * or / case '/': gotOper(ch, 2); // go pop operators break; // (precedence 2) case '(': // it's a left paren theStack.push(ch); // push it break; case ')': // it's a right paren gotParen(ch); // go pop operators break; default: // must be an operand output = output + ch; // write it to output break; } } while (!theStack.isEmpty()) { output = output + theStack.pop(); } System.out.println(output); return output; // return postfix } public void gotOper(char opThis, int prec1) { while (!theStack.isEmpty()) { char opTop = theStack.pop(); if (opTop == '(') { theStack.push(opTop); break; }// it's an operator else {// precedence of new op int prec2; if (opTop == '+' || opTop == '-') prec2 = 1; else prec2 = 2; if (prec2 < prec1) // if prec of new op less { // than prec of old theStack.push(opTop); // save newly-popped op break; } else // prec of new not less output = output + opTop; // than prec of old } } theStack.push(opThis); } public void gotParen(char ch){ while (!theStack.isEmpty()) { char chx = theStack.pop(); if (chx == '(') break; else output = output + chx; } } public static void main(String[] args) throws IOException { String input = "1+2*4/5-7+3/6"; String output; InToPost theTrans = new InToPost(input); output = theTrans.doTrans(); System.out.println("Postfix is " + output + '\n'); } class Stack { private int maxSize; private char[] stackArray; private int top; public Stack(int max) { maxSize = max; stackArray = new char[maxSize]; top = -1; } public void push(char j) { stackArray[++top] = j; } public char pop() { return stackArray[top--]; } public char peek() { return stackArray[top]; } public boolean isEmpty() { return (top == -1); } } }
Parse postfix arithmetic
expressions :
|
No comments:
Post a Comment