Академический Документы
Профессиональный Документы
Культура Документы
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!
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); } }
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)
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; }
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; }
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():
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
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); } } }