Вы находитесь на странице: 1из 18

Table of Contents

lData Structures lStack:


an array based stack: public void push(int val){ s[++tos]=val; } public void pop(){ if(!isEmpty()) tos--; } public int top(){ return s[tos]; } public boolean isEmpty(){ return (tos==-1)? true:false; } Stack Methods: .empty() - Tests if this stack is empty. .peek() - Looks at the object at the top of this stack without removing it from the stack. .pop() - Removes the object at the top of this stack and returns that object as the value of this function. .push() - Pushes an item onto the top of this stack. .search() - Returns the 1-based position where an object is on this stack.

lQueue:
an array based queue: public void insert(int val){ q[++tail]=val; } public void delete(){ if(!isEmpty()){ for(int i=0; i< tail; i++) q[i]=q[i+1]; tail--; } } } public int front(){ return q[0]; } public boolean isEmpty(){ return (tail==-1)? true:false; } queue methods: .add(E e) - Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available. .element() - Retrieves, but does not remove, the head of this queue. .offer(E e) - Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. .peek() - Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. .poll() - Retrieves and removes the head of this queue, or returns null if this queue is empty. .remove() - Retrieves and removes the head of this queue.

l
l

lLinked List:
public void insertEnd(int val){ Node n = new Node(); if(first==null) first=n; else last.next=n; n.data=val; last=n; } public void insertBegin(int val){ Node n = new Node(); n.next=first; if(first==null)last=n; first=n; n.data=val; } public void deleteBegin(){ if(first==null)return; first=first.next; }

public boolean isEmpty(){ return (first==null)? true: false; } Linked list methods: Check book, too many to list!

lPriority queue (Strings, short to long):


// Test.java import java.util.Comparator; import java.util.PriorityQueue; public class Test { public static void main(String[] args) { Comparator<String> comparator = new StringLengthComparator(); PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator); queue.add("short"); queue.add("very long indeed"); queue.add("medium"); while (queue.size() != 0) { System.out.println(queue.remove()); } } } // StringLengthComparator.java import java.util.Comparator; public class StringLengthComparator implements Comparator<String> { @Override public int compare(String x, String y) { // Assume neither string is null. Real code should // probably be more robust if (x.length() < y.length()) { return -1; } if (x.length() > y.length()) { return 1; } return 0; } }

lPriority queue (integers, small to large)


// Test.java import java.util.Comparator; import java.util.PriorityQueue; public class Test { public static void main(String[] args) {

Comparator<String> comparator = new StringLengthComparator(); PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator); queue.add("45"); queue.add("12"); queue.add("14"); while (queue.size() != 0) { System.out.println(queue.remove()); } } } // StringLengthComparator.java import java.util.Comparator; public class StringLengthComparator implements Comparator<String> { @Override public int compare(String x, String y) { // Assume neither string is null. Real code should // probably be more robust if (Integer.parseInt(x) < Integer.parseInt(y)) { return -1; } if (Integer.parseInt(x) > Integer.parseInt(y)) { return 1; } return 0; } }

lTower of Hanoi:
void solve(int n, int i, int j, int k){ if(n==1) movedisk(i,k); else{ solve(n-1,i,k,j); solve(1,i,j,k); solve(n-1,j,i,k); } }

lSorting Algorithms lBubble Sort:


Compares adjacent array elements and exchanges their values if they are out of order. Smaller values bubble up to the top of the array and larger values sink to the bottom public void bubbleSort(){ int temp; for(int j=size-1; j > 0; j--){ for(int i=0; i < j; i++){ if(arr[i] > arr[i+1]){ temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } }

lInstertion Sort:
A simple sorting technique that scans the sorted list, starting at the beginning, for the correct insertion point for each of the items from the unsorted list. public void insertionSort(){ int i,k,temp; for(k=1; k < n; k++){ temp=a[k]; i=k; while(i > 0 && temp < a[i-1]){ a[i]=a[i-1]; i--; } a[i]=temp; } }

lSelection sort:
Selection sort is a relatively easy to understand algorithm. Sorts an array by making several passes through the array, selecting the next smallest item in the array each time and placing it where it belongs in the array. Efficiency is O(n*n) public void selectionSort(){ int i,j,min,temp; for(j=0; j < size-1; j++){ min=j; for(i=j+1; i < size; i++) if(arr[i] < arr[min]) min=i; if(j!=min){ temp=arr[j]; arr[j]=arr[min]; arr[min]=temp; } } }

lMerge Sort:
A sorting technique that sequences data by continuously merging items in the list. Every single item in the original unordered list is merged with another, creating groups of two. Every two-item group is merged, creating groups of four and so on until there is one ordered list. void mergeSort(int first, int last){ int mid; if(first==last) return; mid=(first+last)/2; mergeSort(first,mid); mergeSort(mid+1,last); mergeArray(first,mid,last); }

lQuick sort:
One element, x of the list to be sorted is chosen and the other elements are split into those elements less than x and those greater than or equal to x. These two lists are then sorted recursively using the same algorithm until there is only one element in each list, at which point the sublists are recursively recombined in order yielding the sorted list. void quickSort(int left, int right){ int p=right; if(left >= right) return; if(size <= 20) display(left,right,p); p=partition(left, right); quickSort(left,p-1); quickSort(p+1,right); }

lShell sort:
Divide and conquer approach to insertion sort Instead of sorting the entire array, sort many smaller subarrays using insertion sort before sorting the entire array. public class ShellSort { private long[] data; private int len; public ShellSort(int max) { data = new long[max]; len = 0; } public void insert(long value){ data[len] = value; len++; } public void display() { System.out.print("Data:"); for (int j = 0; j < len; j++) System.out.print(data[j] + " "); System.out.println(""); } public void shellSort() { int inner, outer; long temp; //find initial value of h int h = 1; while (h <= len / 3) h = h * 3 + 1; // (1, 4, 13, 40, 121, ...) while (h > 0) // decreasing h, until h=1 { // h-sort the file for (outer = h; outer < len; outer++) { temp = data[outer]; inner = outer; // one subpass (eg 0, 4, 8) while (inner > h - 1 && data[inner - h] >= temp) { data[inner] = data[inner - h]; inner -= h; } data[inner] = temp; } h = (h - 1) / 3; // decrease h } } }

lHeap sort:
Heap sort does not require any additional storage -build a max-heap from the array -swap first element with last to put largest element at end -build a heap from the unsorted part of the array public static void fnSortHeap(int array[], int arr_ubound){ int i, o; int lChild, rChild, mChild, root, temp; root = (arr_ubound-1)/2; for(o = root; o >= 0; o--){ for(i=root;i>=0;i--){ lChild = (2*i)+1; rChild = (2*i)+2; if((lChild <= arr_ubound) && (rChild <= arr_ubound)){ if(array[rChild] >= array[lChild]) mChild = rChild; else mChild = lChild; } else{ if(rChild > arr_ubound) mChild = lChild; else mChild = rChild; } if(array[i] < array[mChild]){ temp = array[i]; array[i] = array[mChild]; array[mChild] = temp; } } } temp = array[0]; array[0] = array[arr_ubound]; array[arr_ubound] = temp; return; } }

lSorting times
SortBestAverageWorst(Q) SelectionO(n^2)O(n^2)O(n^2)(Q) BubbleO(n)O(n^2)O(n^2) (Q) InsertionO(n)O(n^2)O(n^2)ShellO(n^7/6)O(n^5/4)O(n^2)MergeO(n log n)O(n log n)O(n log n)HeapO(n log n)O(n log n)O(n log n)QuickO(n log n)O(n log n)O(n^2)

lSearch Algorithms lLinear Search (Simple array)


boolean linearSearch(int key){ for(int i=0; i < size; i++){

if(key == arr[i]) return true; } return false; }

lBinary Search:
boolean binarySearch(int key){ int first,last,mid = 0; boolean found = false; first=0; last=size-1; while((!found) && (first <= last)){ mid=first+(last-first)/2; if(arr[mid]==key) found=true; else if(key < arr[mid]) last=mid-1; else if(key > arr[mid]) first=mid+1; } return found; }

lBS Tree lBS Tree Traversal:


lPreorder BS Tree Traversal:
void preOrder(tNode n){ if(n==null) return; visit(n); preOrder(n.left); preOrder(n.right); }

Postorder BS Tree traversal:

inorder BS Tree traversal:

BS Tree Search:
boolean search(int val){ tNode n=root; while(n.data!=val){ if(val < n.data) n=n.left; else n=n.right; if(n==null) return false; } return true; }

lBS Tree insert/delete:

lIterator:
Java iterator is an interface belongs to collection framework allow us to traverse the collection and access the data element of collection without bothering the user about specific implementation of that collection it. Basically List and set collection provides the iterator. You can get Iterator from ArrayList, LinkedList, and TreeSet etc. Map implementation such as HashMap doesnt provide Iterator directory but you can get there keySet or Value Set and can iterator through that collection.

lSyntax:
It comes inside java.util package. Public interface iterator contains three methods:

lboolean hasNext():

this method returns true if iteration has more element.

lObject next(): return the next element in the collection until the hasNext method return true. lremove():
next().

method remove the last element return by the iterator this method only calls once per call to

lHow to create Iterator in Java:


Every collection classes provides an iterator() method that returns an iterator to the beginning of the collection. By using this iterator object, we can access each element in the collection, one element at a time. In general, to use an iterator to traverse through the contents of a collection follow these steps: 1. irst obtain an iterator to the beginning of the collection by calling the collection's iterator( ) 2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. 3. Within the loop, obtain each element by calling next( ).

lJava Iterator tutorial and Example


Example of How to use Iterator in Java

import import import import

java.util.Hashtable; java.util.Iterator; java.util.Set; java.util.Map;

public class StockIteratorExample { public static void main(String[] args) { Hashtable stockTable=new Hashtable(); stockTable.put(new stockTable.put(new stockTable.put(new stockTable.put(new Integer(1), "Two"); Integer(2), "One"); Integer(4), "Four"); Integer(3), "Three");

Set stockSet = stockTable.entrySet(); // Using iterator in hashtable Iterator i= stockSet.iterator(); while(i.hasNext()) { Map.Entry m=(Map.Entry)i.next(); int key = (Integer)m.getKey(); String value=(String)m.getValue(); System.out.println("Key :"+key+" value :"+value); } } }

lWhy use Iterator when we have Enumerator:


Both iterator and enumerator is used for traversing of collection but iterator is more enhanced in terms of extra method remove () it provide us for modify the collection which is not available in enumeration along with that it is more secure it doesnt allow another thread to modify the collection when some another thread is iterating the collection and throws concurrentModificationException. Along with this method name are also very convenient in iterator which is not major difference but make use of iterator more easy.

lWhat is List Iterator in Java?


ListIterator in Java is an iterator which allows user to traverse collection in both direction by using method previous () and next (). You can obtain ListIterator from all List implementation including ArrayList and LinkedList. ListIterator doesnt keep current index and its current position is determined by call to next() or previous() based on direction of traversing.

Вам также может понравиться