Java 9 Data Structures and Algorithms
()
About this ebook
- This book provides complete coverage of reactive and functional data structures
- Based on the latest version of Java 9, this book illustrates the impact of new features on data structures
- Gain exposure to important concepts such as Big-O Notation and Dynamic Programming
This book is for Java developers who want to learn about data structures and algorithms. Basic knowledge of Java is assumed.
Related to Java 9 Data Structures and Algorithms
Related ebooks
Advanced Data Structures and Algorithms: Learn how to enhance data processing with more complex and advanced data structures (English Edition) Rating: 0 out of 5 stars0 ratingsLearning JavaScript Data Structures and Algorithms - Second Edition Rating: 0 out of 5 stars0 ratingsMastering Hibernate Rating: 0 out of 5 stars0 ratingsLearning Functional Data Structures and Algorithms Rating: 0 out of 5 stars0 ratingsSpring Data Rating: 0 out of 5 stars0 ratingsMastering JavaScript Rating: 4 out of 5 stars4/5Everyday Data Structures Rating: 0 out of 5 stars0 ratingsTesting with JUnit Rating: 0 out of 5 stars0 ratingsPython Data Structures and Algorithms Rating: 5 out of 5 stars5/5TypeScript Design Patterns Rating: 0 out of 5 stars0 ratingsIntroduction to JVM Languages Rating: 0 out of 5 stars0 ratingsDistributed Computing in Java 9 Rating: 0 out of 5 stars0 ratingsDjango Design Patterns and Best Practices Rating: 5 out of 5 stars5/5Java Coding Problems: Improve your Java Programming skills by solving real-world coding challenges Rating: 0 out of 5 stars0 ratingsLearn Java 12 Programming: A step-by-step guide to learning essential concepts in Java SE 10, 11, and 12 Rating: 0 out of 5 stars0 ratingsLearning JavaScript Data Structures and Algorithms Rating: 5 out of 5 stars5/5Java: Best Practices to Programming Code with Java Rating: 0 out of 5 stars0 ratingsPractical Java 8: Lambdas, Streams and new resources Rating: 5 out of 5 stars5/5100 Recipes for Programming Java Rating: 5 out of 5 stars5/5Java Multithreading Interview Questions And Answers Rating: 0 out of 5 stars0 ratingsBuilding a RESTful Web Service with Spring Rating: 5 out of 5 stars5/5Java 8 Programmer II Study Guide: Exam 1Z0-809 Rating: 4 out of 5 stars4/5Core Java Professional: For First Time Learner's. Rating: 0 out of 5 stars0 ratingsProgramming Interviews Exposed: Coding Your Way Through the Interview Rating: 0 out of 5 stars0 ratingsGrokking the Java Interview Rating: 0 out of 5 stars0 ratingsFunctional Programming in Scala Rating: 4 out of 5 stars4/5Modern Java in Action: Lambdas, streams, functional and reactive programming Rating: 2 out of 5 stars2/5Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications, and libraries Rating: 3 out of 5 stars3/5Java Core Interview Questions and Answers. Tech interviewer’s notes Rating: 1 out of 5 stars1/5
Programming For You
Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Learn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Learn SAP Basis in 24 Hours Rating: 5 out of 5 stars5/5OCP Oracle Certified Professional Java SE 17 Developer Practice Tests: Exam 1Z0-829 Rating: 5 out of 5 stars5/5Narrative Design for Indies: Getting Started Rating: 4 out of 5 stars4/5Mastering C# and .NET Framework Rating: 5 out of 5 stars5/5Java / J2EE Interview Questions You'll Most Likely Be Asked Rating: 0 out of 5 stars0 ratingsHTML, CSS, & JavaScript All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsPython Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Python for Beginners: A Crash Course to Learn Python Programming in 1 Week Rating: 0 out of 5 stars0 ratingsProblem Solving in C and Python: Programming Exercises and Solutions, Part 1 Rating: 5 out of 5 stars5/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5Accelerated DevOps with AI, ML & RPA: Non-Programmer’s Guide to AIOPS & MLOPS Rating: 5 out of 5 stars5/5TOGAF® Version 9.1 - A Pocket Guide Rating: 0 out of 5 stars0 ratingsPython Games from Zero to Proficiency (Beginner): Python Games From Zero to Proficiency, #1 Rating: 0 out of 5 stars0 ratingsMastering Rust Programming: From Foundations to Future Rating: 0 out of 5 stars0 ratingsExcel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5
Reviews for Java 9 Data Structures and Algorithms
0 ratings0 reviews
Book preview
Java 9 Data Structures and Algorithms - Debasish Ray Chawdhuri
Table of Contents
Java 9 Data Structures and Algorithms
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Why Bother? – Basic
The performance of an algorithm
Best case, worst case and the average case complexity
Analysis of asymptotic complexity
Asymptotic upper bound of a function
Asymptotic upper bound of an algorithm
Asymptotic lower bound of a function
Asymptotic tight bound of a function
Optimization of our algorithm
Fixing the problem with large powers
Improving time complexity
Summary
2. Cogs and Pulleys – Building Blocks
Arrays
Insertion of elements in an array
Insertion of a new element and the process of appending it
Linked list
Appending at the end
Insertion at the beginning
Insertion at an arbitrary position
Looking up an arbitrary element
Removing an arbitrary element
Iteration
Doubly linked list
Insertion at the beginning or at the end
Insertion at an arbitrary location
Removing the first element
Removing an arbitrary element
Removal of the last element
Circular linked list
Insertion
Removal
Rotation
Summary
3. Protocols – Abstract Data Types
Stack
Fixed-sized stack using an array
Variable-sized stack using a linked list
Queue
Fixed-sized queue using an array
Variable-sized queue using a linked list
Double ended queue
Fixed-length double ended queue using an array
Variable-sized double ended queue using a linked list
Summary
4. Detour – Functional Programming
Recursive algorithms
Lambda expressions in Java
Functional interface
Implementing a functional interface with lambda
Functional data structures and monads
Functional linked lists
The forEach method for a linked list
Map for a linked list
Fold operation on a list
Filter operation for a linked list
Append on a linked list
The flatMap method on a linked list
The concept of a monad
Option monad
Try monad
Analysis of the complexity of a recursive algorithm
Performance of functional programming
Summary
5. Efficient Searching – Binary Search and Sorting
Search algorithms
Binary search
Complexity of the binary search algorithm
Sorting
Selection sort
Complexity of the selection sort algorithm
Insertion sort
Complexity of insertion sort
Bubble sort
Inversions
Complexity of the bubble sort algorithm
A problem with recursive calls
Tail recursive functions
Non-tail single recursive functions
Summary
6. Efficient Sorting – quicksort and mergesort
quicksort
Complexity of quicksort
Random pivot selection in quicksort
mergesort
The complexity of mergesort
Avoiding the copying of tempArray
Complexity of any comparison-based sorting
The stability of a sorting algorithm
Summary
7. Concepts of Tree
A tree data structure
The traversal of a tree
The depth-first traversal
The breadth-first traversal
The tree abstract data type
Binary tree
Types of depth-first traversals
Non-recursive depth-first search
Summary
8. More About Search – Search Trees and Hash Tables
Binary search tree
Insertion in a binary search tree
Invariant of a binary search tree
Deletion of an element from a binary search tree
Complexity of the binary search tree operations
Self-balancing binary search tree
AVL tree
Complexity of search, insert, and delete in an AVL tree
Red-black tree
Insertion
Deletion
The worst case of a red-black tree
Hash tables
Insertion
The complexity of insertion
Search
Complexity of the search
Choice of load factor
Summary
9. Advanced General Purpose Data Structures
Priority queue ADT
Heap
Insertion
Removal of minimum elements
Analysis of complexity
Serialized representation
Array-backed heap
Linked heap
Insertion
Removal of the minimal elements
Complexity of operations in ArrayHeap and LinkedHeap
Binomial forest
Why call it a binomial tree?
Number of nodes
The heap property
Binomial forest
Complexity of operations in a binomial forest
Sorting using a priority queue
In-place heap sort
Summary
10. Concepts of Graph
What is a graph?
The graph ADT
Representation of a graph in memory
Adjacency matrix
Complexity of operations in a sparse adjacency matrix graph
More space-efficient adjacency-matrix-based graph
Complexity of operations in a dense adjacency-matrix-based graph
Adjacency list
Complexity of operations in an adjacency-list-based graph
Adjacency-list-based graph with dense storage for vertices
Complexity of the operations of an adjacency-list-based graph with dense storage for vertices
Traversal of a graph
Complexity of traversals
Cycle detection
Complexity of the cycle detection algorithm
Spanning tree and minimum spanning tree
For any tree with vertices V and edges E, |V| = |E| + 1
Any connected undirected graph has a spanning tree
Any undirected connected graph with the property |V| = |E| + 1 is a tree
Cut property
Minimum spanning tree is unique for a graph that has all the edges whose costs are different from one another
Finding the minimum spanning tree
Union find
Complexity of operations in UnionFind
Implementation of the minimum spanning tree algorithm
Complexity of the minimum spanning tree algorithm
Summary
11. Reactive Programming
What is reactive programming?
Producer-consumer model
Semaphore
Compare and set
Volatile field
Thread-safe blocking queue
Producer-consumer implementation
Spinlock and busy wait
Functional way of reactive programming
Summary
Index
Java 9 Data Structures and Algorithms
Java 9 Data Structures and Algorithms
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: April 2017
Production reference: 1250417
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-934-9
www.packtpub.com
Credits
Author
Debasish Ray Chawdhuri
Reviewer
Miroslav Wengner
Commissioning Editor
Kunal Parikh
Acquisition Editor
Chaitanya Nair
Content Development Editor
Nikhil Borkar
Technical Editor
Madhunikita Sunil Chindarkar
Copy Editor
Muktikant Garimella
Project Coordinator
Vaidehi Sawant
Proofreader
Safis Editing
Indexer
Mariammal Chettiyar
Graphics
Abhinash Sahu
Production Coordinator
Nilesh Mohite
Cover Work
Nilesh Mohite
About the Author
Debasish Ray Chawdhuri is an established Java developer and has been in the industry for the last 8 years. He has developed several systems, right from CRUD applications to programming languages and big data processing systems. He had provided the first implementation of extensible business reporting language specification, and a product around it, for the verification of company financial data for the Government of India while he was employed at Tata Consultancy Services Ltd. In Talentica Software Pvt. Ltd., he implemented a domain-specific programming language to easily implement complex data aggregation computation that would compile to Java bytecode. Currently, he is leading a team developing a new high-performance structured data storage framework to be processed by Spark. The framework is named Hungry Hippos and will be open sourced very soon. He also blogs at http://www.geekyarticles.com/ about Java and other computer science-related topics.
He has worked for Tata Consultancy Services Ltd., Oracle India Pvt. Ltd., and Talentica Software Pvt. Ltd.
I would like to thank my dear wife, Anasua, for her continued support and encouragement, and for putting up with all my eccentricities while I spent all my time writing this book. I would also like to thank the publishing team for suggesting the idea of this book to me and providing all the necessary support for me to finish it.
About the Reviewer
Miroslav Wengner has been a passionate JVM enthusiast ever since he joined SUN Microsystems in 2002. He truly believes in distributed system design, concurrency, and parallel computing. One of Miro's biggest hobby is the development of autonomic systems. He is one of the coauthors of and main contributors to the open source Java IoT/Robotics framework Robo4J.
Miro is currently working on the online energy trading platform for enmacc.de as a senior software developer.
I would like to thank my family and my wife, Tanja, for big support during reviewing this book.
www.PacktPub.com
eBooks, discount offers, and more
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1785889346.
If you'd like to join our team of regular reviewers, you can e-mail us at customerreviews@packtpub.com. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
Java has been one of the most popular programming languages for enterprise systems for decades now. One of the reasons for the popularity of Java is its platform independence, which lets one write and compile code on any system and run it on any other system, irrespective of the hardware and the operating system. Another reason for Java's popularity is that the language is standardized by a community of industry players. The latter enables Java to stay updated with the most recent programming ideas without being overloaded with too many useless features.
Given the popularity of Java, there are plenty of developers actively involved in Java development. When it comes to learning algorithms, it is best to use the language that one is most comfortable with. This means that it makes a lot of sense to write an algorithm book, with the implementations written in Java. This book covers the most commonly used data structures and algorithms. It is meant for people who already know Java but are not familiar with algorithms. The book should serve as the first stepping stone towards learning the subject.
What this book covers
Chapter 1, Why Bother? – Basic, introduces the point of studying algorithms and data structures with examples. In doing so, it introduces you to the concept of asymptotic complexity, big O notation, and other notations.
Chapter 2, Cogs and Pulleys – Building Blocks, introduces you to array and the different kinds of linked lists, and their advantages and disadvantages. These data structures will be used in later chapters for implementing abstract data structures.
Chapter 3, Protocols – Abstract Data Types, introduces you to the concept of abstract data types and introduces stacks, queues, and double-ended queues. It also covers different implementations using the data structures described in the previous chapter.
Chapter 4, Detour – Functional Programming, introduces you to the functional programming ideas appropriate for a Java programmer. The chapter also introduces the lambda feature of Java, available from Java 8, and helps readers get used to the functional way of implementing algorithms. This chapter also introduces you to the concept of monads.
Chapter 5, Efficient Searching – Binary Search and Sorting, introduces efficient searching using binary searches on a sorted list. It then goes on to describe basic algorithms used to obtain a sorted array so that binary searching can be done.
Chapter 6, Efficient Sorting – Quicksort and Mergesort, introduces the two most popular and efficient sorting algorithms. The chapter also provides an analysis of why this is as optimal as a comparison-based sorting algorithm can ever be.
Chapter 7, Concepts of Tree, introduces the concept of a tree. It especially introduces binary trees, and also covers different traversals of the tree: breadth-first and depth-first, and pre-order, post-order, and in-order traversal of binary tree.
Chapter 8, More About Search – Search Trees and Hash Tables, covers search using balanced binary search trees, namely AVL, and red-black trees and hash-tables.
Chapter 9, Advanced General Purpose Data Structures, introduces priority queues and their implementation with a heap and a binomial forest. At the end, the chapter introduces sorting with a priority queue.
Chapter 10, Concepts of Graph, introduces the concepts of directed and undirected graphs. Then, it discusses the representation of a graph in memory. Depth-first and breadth-first traversals are covered, the concept of a minimum-spanning tree is introduced, and cycle detection is discussed.
Chapter 11, Reactive Programming, introduces the reader to the concept of reactive programming in Java. This includes the implementation of an observable pattern-based reactive programming framework and a functional API on top of it. Examples are shown to demonstrate the performance gain and ease of use of the reactive framework, compared with a traditional imperative style.
What you need for this book
To run the examples in this book, you need a computer with any modern popular operating system, such as some version of Windows, Linux, or Macintosh. You need to install Java 9 in your computer so that javac can be invoked from the command prompt.
Who this book is for
This book is for Java developers who want to learn about data structures and algorithms. A basic knowledge of Java is assumed.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: We can include other contexts through the use of the include directive.
A block of code is set as follows:
public static void printAllElements(int[] anIntArray){
for(int i=0;i
System.out.println(anIntArray[i]);
}
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
public static void printAllElements(int[] anIntArray){
for(int i=0;i
System.out.println(anIntArray[i]);
}
}
Any command-line input or output is written as follows:
# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: Clicking the Next button moves you to the next screen.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code Download.
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Java-9-Data-Structures-and-Algorithms. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/Java9DataStructuresandAlgorithm. Check them out!
Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/fles/downloads/Java9DataStructuresandAlgorithms_ColorImages.pdf.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at <questions@packtpub.com>, and we will do our best to address the problem.
Chapter 1. Why Bother? – Basic
Since you already know Java, you have of course written a few programs, which means you have written algorithms. Well then, what is it?
you might ask. An algorithm is a list of well-defined steps that can be followed by a processor mechanically, or without involving any sort of intelligence, which would produce a desired output in a finite amount of time. Well, that's a long sentence. In simpler words, an algorithm is just an unambiguous list of steps to get something done. It kind of sounds like we are talking about a program. Isn't a program also a list of instructions that we give the computer to follow, in order to get a desired result? Yes it is, and that means an algorithm is really just a program. Well not really, but almost. An algorithm is a program without the details of the particular programming language that we are coding it in. It is the basic idea of the program; think of it as an abstraction of a program where you don't need to bother about the program's syntactic details.
Well, since we already know about programming, and an algorithm is just a program, we are done with it, right? Not really. There is a lot to learn about programs and algorithms, that is, how to write an algorithm to achieve a particular goal. There are, of course, in general, many ways to solve a particular problem and not all ways may be equal. One way may be faster than another, and that is a very important thing about algorithms. When we study algorithms, the time it takes to execute is of utmost importance. In fact, it is the second most important thing about them, the first one being their correctness.
In this chapter, we will take a deeper look into the following ideas:
Measuring the performance of an algorithm
Asymptotic complexity
Why asymptotic complexity matters
Why an explicit study of algorithms is important
The performance of an algorithm
No one wants to wait forever to get something done. Making a program run faster surely is important, but how do we know whether a program runs fast? The first logical step would be to measure how many seconds the program takes to run. Suppose we have a program that, given three numbers, a, b, and c, determines the remainder when a raised to the power b is divided by c.
For example, say a=2, b=10, and c = 7, a raised to the power b = 2¹⁰ = 1024, 1024 % 7 = 2. So, given these values, the program needs to output 2. The following code snippet shows a simple and obvious way of achieving this:
public static long computeRemainder(long base, long power, long divisor){
long baseRaisedToPower = 1;
for(long i=1;i<=power;i++){
baseRaisedToPower *= base;
}
return baseRaisedToPower % divisor;
}
We can now estimate the time it takes by running the program a billion times and checking how long it took to run it, as shown in the following code:
public static void main(String [] args){
long startTime = System.currentTimeMillis();
for(int i=0;i<1_000_000_000;i++){
computeRemainder(2, 10, 7);
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
On my computer, it takes 4,393 milliseconds. So the time taken per call is 4,393 divided by a billion, that is, about 4.4 nanoseconds. Looks like a very reasonable time to do any computation. But what happens if the input is different? What if I pass power = 1000? Let's check that out. Now it takes about 420,000 milliseconds to run a billion times, or about 420 nanoseconds per run. Clearly, the time taken to do this computation depends on the input, and that means any reasonable way to talk about the performance of a program needs to take into account the input to the program.
Okay, so we can say that the number of nanoseconds our program takes to run is 0.42 X power, approximately.
If you run the program with the input (2, 1000, and 7), you will get an output of 0, which is not correct. The correct output is 2. So, what is going on here? The answer is that the maximum value that a long type variable can hold is one less than 2 raised to the power 63, or 9223372036854775807L. The value 2 raised to the power 1,000 is, of course, much more than this, causing the value to overflow, which brings us to our next point: how much space does a program need in order to run?
In general, the memory space required to run a program can be measured in terms of the bytes required for the program to operate. Of course, it requires the space to at least store the input and the output. It may as well need some additional space to run, which is called auxiliary space. It is quite obvious that just like time, the space required to run a program would, in general, also be dependent on the input.
In the case of time, apart from the fact that the time depends on the input, it also depends on which computer you are running it on. The program that takes 4 seconds to run on my computer may take 40 seconds on a very old computer from the nineties and may run in 2 seconds in yours. However, the actual computer you run it on only improves the time by a constant multiplier. To avoid getting into too much detail about specifying the details of the hardware the program is running on, instead of saying the program takes 0.42 X power milliseconds approximately, we can say the time taken is a constant times the power, or simply say it is proportional to the power.
Saying the computation time is proportional to the power actually makes it so non-specific to hardware, or even the language the program is written in, that we can estimate this relationship by just looking at the program and analyzing it. Of course, the running time is sort of proportional to the power because there is a loop that executes power number of times, except, of course, when the power is so small that the other one-time operations outside the loop actually start to matter.
Best case, worst case and the average case complexity
In general, the time or space required for an algorithm to process a certain input depends not only on the size of the input, but also on the actual value of the input. For example, a certain algorithm to arrange a list of values in increasing order may take much less time if the input is already sorted than when it is an arbitrary unordered list. This is why, in general, we must have a different function representing the time or space required in the different cases of input. However, the best case scenario would be where the resources required for a certain size of an input take the least amount of resources. The would also be a worst case scenario, in which the algorithm needs the maximum amount of resources for a certain size of input. An average case is an estimation of the resources taken for a given size of inputs averaged over all values of the input with that size weighted by their probability of occurrence.
Analysis of asymptotic complexity
We seem to have hit upon an idea, an abstract sense of the running time. Let's spell it out. In an abstract way, we analyze the running time of and the space required by a program by using what is known as the asymptotic complexity.
We are only interested in what happens when the input is very large because it really does not matter how long it takes for a small input to be processed; it's going to be small anyway. So, if we have x³ + x², and if x is very large, it's almost the same as x3. We also don't want to consider constant factors of a function, as we have pointed out earlier, because it is dependent on the particular hardware we are running the program on and the particular language we have implemented it in. An algorithm implemented in Java will perform a constant times slower than the same algorithm written in C. The formal way of tackling these abstractions in defining the complexity of an algorithm is called an asymptotic bound. Strictly speaking, an asymptotic bound is for a function and not for an algorithm. The idea is to first express the time or space required for a given algorithm to process an input as a function of the size of the input in bits and then looking for an asymptotic bound of that function.
We will consider three types of asymptotic bounds—an upper bound, a lower bound and a tight bound. We will discuss these in the following sections.
Asymptotic upper bound of a function
An upper bound, as the name suggests, puts an upper limit of a function's growth. The upper bound is another function that grows at least as fast as the original function. What is the point of talking about one function in place of another? The function we use is in general a lot more simplified than the actual function for computing running time or space required to process a certain size of input. It is a lot easier to compare simplified functions than to compare complicated functions.
For a function f, we define the notation O, called big O, in the following ways:
f(x) = O(f(x)).
For example, x³ = O(x³).
If f(x) = O(g(x)), then k f(x) = O(g(x)) for any non-zero constant k.
For example, 5x³ = O(x³) and 2 log x = O(log x) and -x³ = O(x³)