0% found this document useful (0 votes)
18 views2 pages

Lab 5 Q 8

Uploaded by

Milica Markovic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views2 pages

Lab 5 Q 8

Uploaded by

Milica Markovic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.util.

Random;

class TreeNode {
int key;
TreeNode left, right;

public TreeNode(int item) {


key = item;
left = right = null;
}
}

public class BinarySearchTree {


private TreeNode root;

public BinarySearchTree() {
root = null;
}

// In-order traversal
public void inOrderTraversal() {
inOrderTraversal(root);
System.out.println();
}

private void inOrderTraversal(TreeNode root) {


if (root != null) {
inOrderTraversal(root.left);
System.out.print(root.key + " ");
inOrderTraversal(root.right);
}
}

// Insert a key into the BST


public void insert(int key) {
root = insert(root, key);
}

private TreeNode insert(TreeNode root, int key) {


if (root == null) {
return new TreeNode(key);
}

if (key < root.key) {


root.left = insert(root.left, key);
} else if (key > root.key) {
root.right = insert(root.right, key);
}

return root;
}

// Search for a key in the BST


public boolean search(int key) {
return search(root, key);
}

private boolean search(TreeNode root, int key) {


if (root == null || root.key == key) {
return root != null;
}

if (key < root.key) {


return search(root.left, key);
} else {
return search(root.right, key);
}
}

public static void main(String[] args) {


BinarySearchTree bst = new BinarySearchTree();

// Insert keys
int[] keys = {8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15};
for (int key : keys) {
bst.insert(key);
}

// Perform search(1) 100,000 times and measure time


int repetitions = 100000;

// Measure time for search(1)


long startTime1 = System.nanoTime();
for (int i = 0; i < repetitions; i++) {
bst.search(1);
}
long endTime1 = System.nanoTime();
long duration1 = endTime1 - startTime1;
System.out.println("Time taken for search(1) (average over " + repetitions
+ " repetitions): " + (duration1 / repetitions) + " ns");

// Perform search(15) 100,000 times and measure time


long startTime15 = System.nanoTime();
for (int i = 0; i < repetitions; i++) {
bst.search(15);
}
long endTime15 = System.nanoTime();
long duration15 = endTime15 - startTime15;
System.out.println("Time taken for search(15) (average over " + repetitions
+ " repetitions): " + (duration15 / repetitions) + " ns");
}
}

You might also like