aj unit2 notesjavadatastructures

16
UNIT II - JAVA DATA STRUCTURES Lists Linear Structures Arrays Stack Queue Linked List Ordered & Unordered Structures Order Structure Un Ordered Structure Sorting Trees Binary Tree Example of a binary tree Operations Implementations Binary Search Tree (BST) .

Upload: arthik-daniel

Post on 22-Nov-2014

227 views

Category:

Technology


0 download

DESCRIPTION

Java Data Structures

TRANSCRIPT

Page 1: Aj unit2 notesjavadatastructures

UNIT II - JAVA DATA STRUCTURES

ListsLinear Structures

ArraysStackQueueLinked List

Ordered & Unordered StructuresOrder StructureUn Ordered Structure

SortingTrees

Binary TreeExample of a binary treeOperationsImplementationsBinary Search Tree (BST)

.

Page 2: Aj unit2 notesjavadatastructures

Lists

Collections API Revisit?

List Abstract Data Type (ADT)

• A list a collection of items in which the items have a position• We keep “to-do” lists, shop with a grocery list, and invite a list of friends to a party

• Types of Lists– Ordered Lists - (implements Comparable Interface)

• An ordered list is kept in order based on characteristics of the elements in the list, e.g.alphabetical order for names

– Unordered Lists• They are stored in an order that is externally controlled by how and when the elements areadded to the list

– Indexed Lists

Topics Discussed in URL:● List Implementations● Adding and Accessing Elements● Removing Elements● Generic Lists

A List represents a data structure which allows to dynamically add, access and remove objects of the same type. Adding objects to thelist is usually done via the add() method. The get(int i) method allows to retrieve the element at position i. Remove objects from thelist is usually done via the remove(int i) method which removes the element at position i.

Below is a sample program that explains the following:● Custom List Implementation (using Arrays) which allows Adding, Accessing & Removing Elements● Test Application that uses the above Customized List

Page 3: Aj unit2 notesjavadatastructures

MyList.java

package list;

import java.util.Arrays;import java.util.Iterator;

/** * Created by user on 2/15/14. */public class MyList<E> { private int size = 0; private static final int DEFAULT_CAPACITY = 10; private Object elements[];

public MyList() { elements = new Object[DEFAULT_CAPACITY]; }

public void add(E e) { if (size == elements.length) { ensureCapa(); } elements[size++] = e; }

private void ensureCapa() { int newSize = elements.length * 2; elements = Arrays.copyOf(elements, newSize); }

@SuppressWarnings("unchecked") public E get(int i) { if (i >= size || i < 0) { throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i); } return (E) elements[i]; }

public E remove(int i) { if (i >= size || i < 0) { throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i); } size++; E oldValue = (E) elements[i];

int numMoved = size - i - 1; if (numMoved > 0) System.arraycopy(elements, i + 1, elements, i, numMoved); elements[--size] = null; return oldValue; }

@Override public String toString() { String temp = new String(); temp = "[";

for (int i = 0; i < elements.length; i++) { if (elements[i] != null) temp = temp + " "+ (E) elements[i] ; }

Page 4: Aj unit2 notesjavadatastructures

temp = temp + "]"; return temp; }

}

The following show contains a small test for the data structure. I use in the first test the MyList implementation and in the second testthe standard Java List implementation.

MyMainListTest.java

package list;

import com.sun.org.apache.xpath.internal.SourceTree;

import java.util.ArrayList;import java.util.List;

/** * Created by user on 2/15/14. */public class MyMainListTest {

public static void main(String[] args) { MyMainListTest myMainListTest = new MyMainListTest(); System.out.println("Testing MyList"); try { myMainListTest.testMyList(); } catch (Exception e) { System.out.println("MyList " + e); } System.out.println("Testing StandardList"); try { myMainListTest.testStandardList(); } catch (Exception e) { System.out.println("StandardList " + e); }

}

public void testMyList() { MyList<Integer> list = new MyList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(3); list.add(4); list.add(2); list.add(3); list.add(3); list.add(4); list.add(2); list.add(3); list.add(3); list.add(4); System.out.println(list); //Remove element on 4th Index. list.remove(4); System.out.println(list);

System.out.println(list.get(1));

Page 5: Aj unit2 notesjavadatastructures

System.out.println(list.get(6)); System.out.println(list.get(20));//Throws IndexOutOfBoundsException System.out.println(list.get(-1));//Throws IndexOutOfBoundsException }

public void testStandardList() { List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(3); list.add(4); list.add(2); list.add(3); list.add(3); list.add(4); list.add(2); list.add(3); list.add(3); list.add(4); System.out.println(list); //Remove element on 4th Index. list.remove(4); System.out.println(list);

System.out.println(list.get(1)); System.out.println(list.get(6)); System.out.println(list.get(20));//Throws IndexOutOfBoundsException System.out.println(list.get(-1));//Throws IndexOutOfBoundsException }}

Page 6: Aj unit2 notesjavadatastructures

Linear Structures

Arrays

Arrays are special data types that let us store specified number of variables from the same type using one variablename.

An array is a sequence of data item of homogeneous value(same type).

Why Arrays?Imagine the situation that you need to store 20 names of students as strings and 20 integers as marks, then you need todefine 40 variables, and this is clearly very hard and not practical, in such case you need to use arrays.

Arrays are indexed data types.

As Figure shows, the size of an array is fixed, we will refer to array maximum size as array length , it is also clear thatindices of an array are zero-based, that is, they start from 0 to length – 1;for example, the array shown in Figure has alength of 10 (stores up to 10 elements), and the last index is 9

Arrays are of two types:1. One-dimensional arrays2. Multidimensional arrays

One-Dimensional Arrays● Declaration● Initialization (Construction)● Accessing Elements (Read / Write)

Multidimensional Arrays (Arrays of Arrays)● Declaration● Initialization (Construction)● Accessing Elements (Read / Write)

Page 7: Aj unit2 notesjavadatastructures

http://www.tutorialspoint.com/java/util/arraylist_get.htm

Employee.javapublic class Employee implements Comparable {

int EmpID; String Ename; double Sal; static int i;

public Employee() { EmpID = i++; Ename = "dont know"; Sal = 0.0; }

public Employee(String ename, double sal) { EmpID = i++; Ename = ename; Sal = sal; }

public String toString() { return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal" + Sal; }

public int compareTo(Object o1) { if (this.Sal == ((Employee) o1).Sal) return 0; else if ((this.Sal) > ((Employee) o1).Sal) return 1; else return -1; }}

ComparableDemo.java

import java.util.*;

public class ComparableDemo{

public static void main(String[] args) { List ts1 = new ArrayList(); ts1.add(new Employee ("Tom",40000.00)); ts1.add(new Employee ("Harry",20000.00)); ts1.add(new Employee ("Maggie",50000.00)); ts1.add(new Employee ("Chris",70000.00)); Collections.sort(ts1);

Page 8: Aj unit2 notesjavadatastructures

Iterator itr = ts1.iterator();

while(itr.hasNext()){ Object element = itr.next(); System.out.println(element + "\n"); } }}

Output:

EmpID 1Ename HarrySal20000.0

EmpID 0Ename TomSal40000.0

EmpID 2Ename MaggieSal50000.0

EmpID 3Ename ChrisSal70000.0

http://math.hws.edu/javanotes/c7/index.htmlhttp://math.hws.edu/javanotes/c7/s3.htmlhttp://math.hws.edu/javanotes/c7/s5.html

Stack

Stack Implementation using Arrayshttp://www.vogella.com/tutorials/JavaDatastructures/article.htmlhttp://www.youtube.com/watch?v=sFVxsglODoo

http://www.studytonight.com/data-structures/stack-data-structurehttp://tutorials.jenkov.com/java-collections/stack.htmlhttp://math.hws.edu/javanotes/c9/s3.html

Queue

Queue Implementation using Arrayshttp://www.youtube.com/watch?v=okr-XE8yTO8

Page 9: Aj unit2 notesjavadatastructures

http://www.studytonight.com/data-structures/queue-data-structurehttp://tutorials.jenkov.com/java-collections/queue.htmlhttp://math.hws.edu/javanotes/c9/s3.html

Linked List

- Insert at Head- Insert at Last (Append)- Insert Middle Element- Insert After Element- Insert Before Element- Delete Head- Delete Last Element- Delete Middle Element

http://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.htmlhttp://www.idevelopment.info/data/Programming/data_structures/java/LinkedList/LinkedList.shtmlhttp://math.hws.edu/javanotes/c9/s2.htmlhttp://www.tutorialspoint.com/java/java_linkedlist_class.htm

Page 10: Aj unit2 notesjavadatastructures

Ordered & Unordered Structures

Order StructureList--an ordered collection, duplicates are allowed. Topic already discussed earlier.Below are the 4 possible implementations of List.

List listA = new ArrayList();List listB = new LinkedList();List listC = new Vector();List listD = new Stack();

http://tutorials.jenkov.com/java-collections/list.html

Un Ordered Structure

Set--An unordered collection with no duplicates.Below are the 4 possible implementations of Set.

Set setA = new EnumSet();Set setB = new HashSet();Set setC = new LinkedHashSet();Set setD = new TreeSet();

http://tutorials.jenkov.com/java-collections/set.htmlhttp://www.vogella.com/tutorials/JavaDatastructures/article.html

Page 11: Aj unit2 notesjavadatastructures

Sorting

General Explanation for Various Sorting Algorithms:

Bubble Sorthttp://www.youtube.com/watch?v=8Kp-8OGwphYSelection Sort:http://www.youtube.com/watch?v=f8hXR_HvyboInsertion Sort:http://www.youtube.com/watch?v=DFG-XuyPYUQMerge Sort:http://www.youtube.com/watch?v=EeQ8pwjQxTM

Student Assignment: Lab programs on various Sorting Algorithms (Thursday Lab HR)Unit 2 question bNk 16 mark notes submission (Friday by EOD)

Source Code for Sorting Algorithms

Bubble Sorthttp://www.algolist.net/Algorithms/Sorting/Bubble_sorthttp://www.sorting-algorithms.com/bubble-sort

Selection Sort:http://www.youtube.com/watch?v=f8hXR_Hvybohttp://www.algolist.net/Algorithms/Sorting/Selection_sorthttp://www.sorting-algorithms.com/selection-sort

Merge Sort:http://www.youtube.com/watch?v=EeQ8pwjQxTMhttp://www.algolist.net/Algorithms/Merge/Sorted_arrayshttp://www.sorting-algorithms.com/merge-sort

Insertion Sort:http://www.youtube.com/watch?v=DFG-XuyPYUQhttp://www.algolist.net/Algorithms/Sorting/Insertion_sorthttp://www.sorting-algorithms.com/insertion-sort

Page 12: Aj unit2 notesjavadatastructures

Trees

Binary Tree

Binary tree is a widely-used tree data structure. Feature of a binary tree, which distinguish it from common tree, is that each node has at most two children. Each binary tree has following groups of nodes:

● Root: the topmost node in a tree. It is a kind of "main node" in the tree, because all other nodescan be reached from root. Also, root has no parent. It is the node, at which operations on treebegin (commonly).

● Internal nodes: these nodes has a parent (root node is not an internal node) and at least one child.● Leaf nodes: these nodes has a parent, but has no children.

Example of a binary tree

OperationsBasically, we can only define traversals for binary tree as possible operations: root-left-right (preorder), left-right-root (postorder) and left-root-right (inorder) traversals. We will speak about them in detail later.

Implementations● Binary Search Tree (BST)

Binary Search Tree (BST)

General Idea of Trees:http://www.youtube.com/watch?v=rSlFhunlpzISource Code for Binary Search Treehttp://www.youtube.com/watch?v=M6lYob8STMIhttp://www.youtube.com/watch?v=UcOxGmj45AA

public class BinaryTree {

Node root;

public void addNode(int key, String name) {

// Create a new Node and initialize it

Node newNode = new Node(key, name);

Page 13: Aj unit2 notesjavadatastructures

// If there is no root this becomes root

if (root == null) {

root = newNode;

} else {

// Set root as the Node we will start// with as we traverse the tree

Node focusNode = root;

// Future parent for our new Node

Node parent;

while (true) {

// root is the top parent so we start// there

parent = focusNode;

// Check if the new node should go on// the left side of the parent node

if (key < focusNode.key) {

// Switch focus to the left child

focusNode = focusNode.leftChild;

// If the left child has no children

if (focusNode == null) {

// then place the new node on the left of it

parent.leftChild = newNode;return; // All Done

}

} else { // If we get here put the node on the right

focusNode = focusNode.rightChild;

// If the right child has no children

if (focusNode == null) {

// then place the new node on the right of it

parent.rightChild = newNode;return; // All Done

}

}

Page 14: Aj unit2 notesjavadatastructures

}}

}

// All nodes are visited in ascending order// Recursion is used to go to one node and// then go to its child nodes and so forth

public void inOrderTraverseTree(Node focusNode) {

if (focusNode != null) {

// Traverse the left node

inOrderTraverseTree(focusNode.leftChild);

// Visit the currently focused on node

System.out.println(focusNode);

// Traverse the right node

inOrderTraverseTree(focusNode.rightChild);

}

}

public void preorderTraverseTree(Node focusNode) {

if (focusNode != null) {

System.out.println(focusNode);

preorderTraverseTree(focusNode.leftChild);preorderTraverseTree(focusNode.rightChild);

}

}

public void postOrderTraverseTree(Node focusNode) {

if (focusNode != null) {

postOrderTraverseTree(focusNode.leftChild);postOrderTraverseTree(focusNode.rightChild);

System.out.println(focusNode);

}

}

public Node findNode(int key) {

// Start at the top of the tree

Node focusNode = root;

// While we haven't found the Node

Page 15: Aj unit2 notesjavadatastructures

// keep looking

while (focusNode.key != key) {

// If we should search to the left

if (key < focusNode.key) {

// Shift the focus Node to the left child

focusNode = focusNode.leftChild;

} else {

// Shift the focus Node to the right child

focusNode = focusNode.rightChild;

}

// The node wasn't found

if (focusNode == null)return null;

}

return focusNode;

}

public static void main(String[] args) {

BinaryTree theTree = new BinaryTree();

theTree.addNode(50, "Boss");

theTree.addNode(25, "Vice President");

theTree.addNode(15, "Office Manager");

theTree.addNode(30, "Secretary");

theTree.addNode(75, "Sales Manager");

theTree.addNode(85, "Salesman 1");

// Different ways to traverse binary trees

// theTree.inOrderTraverseTree(theTree.root);

// theTree.preorderTraverseTree(theTree.root);

// theTree.postOrderTraverseTree(theTree.root);

// Find the node with key 75

System.out.println("\nNode with the key 75");

System.out.println(theTree.findNode(75));

}

Page 16: Aj unit2 notesjavadatastructures

}

class Node {

int key;String name;

Node leftChild;Node rightChild;

Node(int key, String name) {

this.key = key;this.name = name;

}

public String toString() {

return name + " has the key " + key;

/* * return name + " has the key " + key + "\nLeft Child: " + leftChild + * "\nRight Child: " + rightChild + "\n"; */

}

}