0% found this document useful (0 votes)
133 views198 pages

Veerachary CBCS JAVA III Sem-Watermark

The document provides an overview of the syllabus for a course on data structures using Java. It covers 4 units: 1) Introduction to Java concepts like classes, objects, inheritance and exceptions. 2) Fundamental data structure concepts and linear data structures using arrays. 3) Non-linear data structures like stacks, queues and linked lists and recursion. 4) Trees, graphs, searching and sorting algorithms. It also lists reference books for the course and provides details on object-oriented programming concepts in Java like encapsulation, polymorphism and inheritance.

Uploaded by

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

Veerachary CBCS JAVA III Sem-Watermark

The document provides an overview of the syllabus for a course on data structures using Java. It covers 4 units: 1) Introduction to Java concepts like classes, objects, inheritance and exceptions. 2) Fundamental data structure concepts and linear data structures using arrays. 3) Non-linear data structures like stacks, queues and linked lists and recursion. 4) Trees, graphs, searching and sorting algorithms. It also lists reference books for the course and provides details on object-oriented programming concepts in Java like encapsulation, polymorphism and inheritance.

Uploaded by

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

downloaded from: www.sucomputersforum.

com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

DATA STRUCTURES using JAVA


Syllabus
Unit-I: Overview of Java (JRE and JDK), Installation of Java, Byte Code, Data Types &
Variables, control statements, Operators, Classes and Objects, Declaring classes, Class
members, Interface and Enums. Object orientation, Encapsulation, Inheritance, Polymorphism,
Strings, StringBuffer, Exceptions, Exception Handling, Deadlock.
Unit-II: Fundamental concepts: Introduction to Data Structures, Types of Data Structures,
Introduction to Algorithm, Pseudo code, Flow chart, Analysis of Algorithms. Linear Data
Structure Using Arrays: 1-D Arrays, 2-D Arrays, N-D Arrays, Memory representation and
Address Calculation of 1-D, 2-D, N-D Arrays, Concept of ordered List, Pros and Cons of
Arrays. Stacks: concept, Primitive Operations, Abstract Data type, Representation Stacks Using
Arrays, Prefix, Infix, Postfix Notations for Arithmentic Expression, Applications of Stacks-
Converting Infix Expression to Postfix Expression, Evaluating the Postfix Expression.
Unit-III: Recursion: Introduction, Use of Stack in Recursion, Variants of Recursion, Execution
of Recursive Calls, Recursive Function, Iteration versus Recursion. Queues: Concept, primitive
Operations, Abstract Data Type, Representation Queues Using Arrays, Circular Double Ended
Queue, Applications of Queues. Linked List: Introduction, Concept, Terminology, Primitive
Operation creating, inserting, deleting, traversing, Representation of Linked List, Linked List
Abstract Data Type, Linked List Variants Singly Linked List, Doubly linked List , Linear and
Circular Linked List, Representation Stacks and Queues Using Linked Singly Lists, Application
of Linked List.
Unit-IV: Trees: Introduction, Representation of a General Trees, Binary Tree Introduction
Binary Tree Abstract Data Type, Implementation of Binary Tree, Binary Tree Traversals -
preorder, inorder, postorder Traversals, Applications of Binary Trees Briefly. Graphs:
Introduction, Graph abstract data Type, Representation of Graphs, Graph traversal- Depth-
First Search, Breadth-First Search, Spanning Treee - Prim’s Algorithm, Kruskal’s Algorithm.
Searching and Sorting: Sequential (Linear) Search, Binary search, Bubble Sort , Insertion Sort,
Selection Sort, Quick Sort, Merge Sort, and Comparison of Sorting Techniques, Heaps:
Concept, Implementation, Heap Sort
Reference Books:
1. E.Balaguruswamy, Programming with java, A primer, 3e, TATA McGraw-Hill Company (2008).
2. Robert Lafore, Data Structures& Algorithms in Java, Second Edition, Pearson Education (2008).
3. John R. Hubbard, Programming with Java, Second Edition, Schaum’s outline Series, Tata McGrawhill
(2007).
4. Timothy Budd, Understanding object oriented programming with Java, Pearson Education (2007).
5. Adam Drozdek, Data Structures and Algorithms in Java, Second edition, Cengage Learning (2008).
6. John R. Hubbard, Anita Hurry, Data Structures with Java, Pearson Education (2008).
7. Jana, Java and Object Oriented Programming Paradigm, PHI (2007).
8. Deitel & Deitel. Java TM: How to Program, 7th Edition, PHI (2008).
9. Samatha, Classic Data Structures, PHI (2005).
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 1
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

UNIT- I
Basic concepts of Object Oriented Programming (OOPs Concepts):
The basic concepts of OOP:
Objects
Classes
Data Abstraction
Data Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Massage passing
1. Objects: Objects are basic run time entities in an object oriented system. The objects are
representing a person, place, a bank account, and a table of data or any item that the program
may handle.
Objects are chosen such that they match closely with real world objects. Objects takes up
space in the memory and have an associated address. While program is executing the objects
may interact with each other by sending messages. Each object contains data and code to
manipulate the data. Objects are represented as shown below.

Person Object

Name
Basic pay Data
salary()
tax() Methods
2. Classes: A class may be thought of as a “data type” and an object as a “variable” of that type.
(OR) Class is a group of objects that have the same properties. Once a Class has been defined,
we can create any number of objects belonging to that class. A class is thus a collection of
objects of similar type.
Example: mango, orange and apple are members of the class “Fruits”
fruit mango;
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 2
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Classes are User-defined data types and behave like the built-in types of programming
language.
3. Data Abstraction: Abstraction refers to the act of representing essential features without
including the background details. Classes use the concept of abstraction.

4. Data Encapsulation: The mechanism of combining the data and methods into a single unit
(called class) is known as Data encapsulation. Data encapsulation is the most striking feature of
a class. The data not accessible to the outside world and only those methods, which are
wrapping in the class, can access it. The insulation of the data from direct access by program is
called Data Hiding.

5. Polymorphism: Polymorphism is another important OOPs concept. Polymorphism means


the ability to take more than one form. For example, an operation may exhibit different
behaviors in different instances (objects). The behavior depends upon the types of data used in
the operation
Example: Consider the operation of addition for two numbers, the operation generates a
sum. If the operands are strings, then the operation would produce a third string by
concatenation Shape
Draw ( )

Circle object Box object Triangle object


Draw (circle) Draw (box) Draw (Triangle)

The figure illustrates, that a single function name can be used to handle different number
and different type of arguments.

6. Inheritance: Inheritance is the process by which objects of one class can acquire the
properties of objects of another class. Inheritance supports the concept of hierarchical
classification.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 3


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

For example, the bird parrot is derived from the class flying birds, which is again a part
of class bird. Bird
Attributes:
Feathers
Lay eggs

Flying Birds Non flying Birds

Attributes: Attributes:

Parrot Crow Penguin Kiwi

Attributes: Attributes: Attributes: Attributes:

Property of Inheritance

Parent
Parent class or Base class or super class Features

Parent
features
Child class or Derived class or sub class
Child features

Inheritance provides the concept of reusability. This means that we can add additional
features to an existing class without modifying it. This is possible by deriving a new class
(child) from existing one (parent). The new class will have the combined features of both the
classes.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 4


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

7. Dynamic Binding: Binding refers to the linking of a procedure call to the code to be
executed in response to the call. Dynamic binding means the code associated with a given
procedure call is not known until the time of the call at run time. It is associated with
polymorphism and inheritance.
For example, in the previous example every object have draw( ) method. Draw procedure
will be redefined in each class that defines the object. At runtime the code matching the objects
under current reference will be called.
8. Message Passing: Another important feature of OOPs is massage passing. By using this
facility objects communicate with each other by sending and receiving information much the
same way as people pass messages to one another. This concept makes it easier to talk about
building systems that directly model their real world counter parts. This technique involves the
following 3 steps.
i) Creating classes that define objects and their behavior.
ii) Creating objects from class definition.
iii) Establish communication between objects.

Message Method( )

Sending Object Receiving Object


Message passing involves specifying name of an object and the name of the method
(message) and information to be sent.
For example consider the statement: Employee. Salary (name);

Object message information

JAVA HISTORY:
Java is a general purpose; object oriented programming language developed by sun
Microsystems of USA in 1991. Originally called oak by James Gosling, one of the inventors of
the language, java was designed for the development of software for consumer electronic
devices likes TV’s, VCR s, toasters and such other electronic machines.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 5
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

The java team which included Patrick Naughton discovered that the existing languages
like C and C++ had limitations in terms of both reliability and portability. However, they
modeled their new language Java on C and C++ but removed a number of features of C and
C++ that were considered as sources of problems and thus made Java a really simple, reliable,
portable and powerful language.
Java milestones:

YEAR Development
1990 Sun Microsystems decided to develop special software that could be used to
manipulate consumer electronic devices. A team of sun micro systems programmer
headed by James Gosling was formed to undertake this task
1991 After exploring the possibility of using the most popular object-oriented
language C++ , the team announced a new language named “oak”
1992 The team known as Green Project Team by sun, demonstrated the application
of their new language to control a list of home applications using hand-held
device with a tiny touch-sensitive screen
1993 The world wide web (www) appeared on internet and transformed the text-
based internet into a graphical-rich environment. The Green Project team came up
with the Idea of developing Web applets using the new language that could run on
all types of computers connected to internet.
1994 The team developed a web browser called “Hat java’ to locate and run applet
programs on internet. Hot java demonstrated the power of new language, thus
making it instantly popular among the internet users
1995 Oak was renamed “java”, due to some legal snags (problems), Java was just a
name and is not acronym. Many popular companies include Netscape and
Microsoft announced their support of java.
1996 Java established itself not only as leader for internet programming but also as
general-purpose, object-oriented programming language. Sun releases JDK 1.0
1997 Sun releases JDK 1.1
1998 Sun releases Java 2 with version 1.2 of the Software Development Kit (SDK) 1.2
1999 Sun releases Java 2 platform Standard Edition (J2SE) and Enterprise Edition
(J2EE)
2000 J2SE with SDK 1.3 was released.
2002 J2SE with SDK 1.4 was released.
2004 J2SE with JDK 5.0 was released. This is known as J2SE 5.0
The most powerful feature of Java is that it is a “Platform- Neutral” language. Java is the
first programming language that is not tied to any particular operating system. Programs
developed in Java can be executed anywhere on any system.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 6


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Java features (or) Java buzzwords (or) Java advantages:


The inventor of java wanted to design a language which could offer solutions to some of the
problems encountered in modern programming. They wanted to language to be not only reliable
,portable, and distributed but also simple, compact and iterative .Sun micro systems officially
describes Java with following features:
 Compiled and Interpreted
 Platform-Independent and Portable
 Object-Oriented
 Robust and Secure
 Distributed
 Familiar, Simple and Small
 Multithreaded and Interactive
 High performance
 Dynamic and Extensible
Compiled and Interpreted: Usually a computer language is either compiled or interpreted.
Java combines both these approaches thus making Java a two-stage system. First Java compiler
translates source code into what is known as byte code instructions. Byte code not machine
instructions and therefore, in the second stage Java interpreter translates byte code into machine
code that can be directly executed by machine that running java program. So we can say that
java is both compiled and interpreted language.
Java compiler Java Interpreter
Source code Byte code Machine code (Output)

Platform-Independent and Portable: The most significant contribution of java over other
languages is portability. Java programs can be easily moved from one computer system to
another, anywhere and anytime. Changes and upgrades in operating systems, processors and
system resources will not force any changes in java programs.
Java ensures portability in two ways. First java compiler generates byte code instructions
that can be implemented on any machine. Secondary, the size of primitive data types are
machine independent.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 7


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Object-Oriented: Java is a true object oriented language. Almost everything in java is an


object. All program code and data resides with in an object. Java comes with an extensive set of
classes, arranged in packages.
Robust and Secure: Java is robust language. It provides many safeguards to ensure reliable
code. It has strict compile time and runtime checking for data types. It is designed as garbage
collected language relieving the programmers virtually all memory management problems.
Security becomes an important issue for a language that is used for programming on
internet. Threat of viruses and abuse of resources are everywhere. The absence of pointers in
Java ensures that programs can not gain access to memory locations without proper
authorization. Java system not only verifies all memory access but also ensure that no viruses
are communicated.
Distributed: Java is designed as distributed language for creating applications on networks. It
has the ability to share both data and programs.
Simple, Small and Familiar: Java is a small and simple language. Many complex features of C
and C++ are not part of java.
Familiarity is another important feature of java. To make the language look familiar to
the existing programmer, java uses many constructs of C and C++. Java code “look like C++”
code because java is a simplified version of C++.
Multithreaded and interactive: Multithreaded means handling multiple tasks simultaneously.
Java supports multithreaded programs. This means that we need not wait for the application to
finish one task before beginning another.
Example: we can listen to an audio clip while scrolling a page and at the same time download
an applet from distant computer.
The java runtime comes with tools that support multi process synchronization and
construct smoothly running interactive system.
High performance: Java performance is impressive for an interpreted language mainly due to
the use of intermediate byte code. As described earlier, the Java byte code was carefully

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 8


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

designed so that it would be easy to translate directly into native machine code for very high
performance by using a just-in-time compiler. Java architecture is also designed to reduce
overheads during runtime.
Dynamic & Extensible: Java is a dynamic language. Java is capable of dynamically linking in
new class libraries, methods and objects.
Java supports functions written in other languages such as C and C++. These functions
are known as native methods.
Differences between Java and C:
Java is a lot like C but major difference between java and C is that Java is an object-
oriented language
 Java does not include structures, unions and enum.
 Java does not support type def, size of, go to
 Java does not define the type modifier keywords auto, extern, register, signed, and
unsigned.
 Java does not support explicit pointer.
 Java does not include a preprocessor and therefore we cannot use #define, #include,
#ifdef statements.
 Java requires that the functions with no arguments must be declared with empty
parenthesis and not with the void keyword as done in C.
 Java adds new operators such as instance of and >>>.
 Java add labeled break and continue statements.
 Java adds many features that required for object-oriented programming
Differences between Java and C++:
Java is true object oriented language while C++ basically C with object-oriented extension.
Java appears to be similar to C++ when we consider only the “extension” part of C++.
Listed below are some major C++ features that we intentionally omitted from java or
significantly modified.
 Java does not support operator overloading.
 Java does not have template classes as in C++.
 Java does not support multiple inheritances of classes. This is accomplished using a new
feature called “interface”
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 9
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

 Java does not support global variables. Every variable and method is declared with in a
class and form part of that class.
 Java does not use pointers. C++
 There are no header files in java. C
Java

Overlapping C, C++ and Java

 Overview of Java Language


Java is general purpose, object-oriented programming language. We can develop two
types of java programs
Stand-alone applications
Web applets
To execute the java program involves two steps:
 Compiling source code into byte code using javac compiler
 Executing the byte code program using java interpreter

Java
Source
Code

Java
Compiler
Application
Applet Type Type

Java enabled Java


Web browser Interpreter

Output Output

Fig: Two ways of using java

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 10


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

 Java Environment
Java environment includes a large number of development tools and hundreds of classes
and methods. The development tools are part of the system known as Java Development Kit
(JDK) and the classes and methods are parts of the Java Standard Library (JSL) also known
as the Application Programming Interface (API).
Java Development Kit (JDK): The JDK comes with a collection of tools that are used for
developing and running Java programs. They include:
1. appletviewer: it enables us to run Java applets.
2. javac (java compiler): which translates Java source code to byte code.
3. java (java interpreter): which runs applets and applications by reading and interpreting
byte code files.
4. javadoc: creates HTML format documentation from java source code files.
5. javah: produces header files for use with native methods.
6. javap (java disassembler): which enables us to convert byte code files into a program
description.
7. jdb (java debugger): which helps us to find errors in our program.
The way these tools are applied to build and run application programs is illustrated in
following figure.
Text Editor

Java source code javadoc HTML files

javac

Java class file javah Header files

java jdb

Java program output

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 11


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Application Program Interface (API): API includes hundreds of classes and methods grouped
into several functional packages. Most commonly used packages are:
1. Language support package: A collection of classes and methods required for
implementing basic features of java.
2. Utilities package: A collection of classes to provide utility functions such as date and
time functions.
3. Input / Output package: A collection of classes required fir input/ output manipulation.
4. Networking package: A collection of classes for communicating with other computer
via internet.
5. AWT package: The Abstract Window Tool kit package contains classes that implements
platform independent graphical user interface.
6. Applet package: This includes a set of classes that allows us to create Java applets.

 Java Runtime Environment(JRE)


Java Runtime Environment (JRE) facilitates the execution of programs developed in java.
It primarily comprises of the following.
 Java Virtual Machine(JVM): It is a program that interprets the intermediate Java byte
code and generates the desired output. It is because of bytecode and JVM concepts that
programs written in Java are highly portable.
 Runtime class libraries: There are a set of core class libraries that are required for the
execution of Java programs.
 User Interface toolkits: AWT and Swing areexamples of toolkits that support varied
input methods for the users to interact with the application program.
 Deployment technologies: JRE comprises the following key deployment technologies:
 Java plug-in: Enables the execution of Java applet on the browser.
 Java Web Start: Enables remote-deployment of an application. With Web Start,
users can launch an application directly from the Web browser without going
through the installation procedure.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 12
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Installation of Java
The first step in the installation of Java is to download the Java Development Kit (JDK)
from the java.sun.com. We must choose the right version of Java at the time of download
keeping in mind the existing platform. Once the set up file downloaded, we may proceed to
install Java.
To install Java, we need to perform the following steps:
1. Double-click the .exe file to initiate the installation procedure. The welcome screen
appears as shown below.

2. The Welcome screen shows the licensing terms and conditions. Click the Accept button
to begin Java installation. The progress screen appears as shown below.

3. The progress screen depicts the percentage of installation that has been completed. Once
the installation is complete, the complete screen appears as shown below.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 13


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

4. The Complete screen depicts the successful installation of Java on the computer system.
Click the Finish button to end the installation process.

Byte code
Bytecode is nothing but intermediate representation of Java source code which is
produced by the Java compiler by compiling the source code. This byte code is machine
independent code. It is not a completely compiled code but it is an intermediate code
somewhere in the middle which is later interpreted and executed by JVM.
Bytecode is a machine code for JVM. But the machine code is platform specific whereas
bytecode is platform independent that is the main difference between them. It is stored in
“.class” file which is created after compiling the source code.

Java tokens
Java programs are a collection of classes. The smallest individual unit in the program
is known as token. Java language includes the following tokens:
1. White space, 2. Identifiers, 3. Literals, 4. Operators, 5. Separators, and 6. Keywords.
1. White space: Java is a free-form language. This means that you do not need to follow any
special indentation rules. For example, if the program have been written all on one line or in any
other strange way you felt like typing it, as long as there was at least one white space character
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 14
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

between each token that was not already delineated by an operator or separator. In Java, white
space is a space, tab, or new line.
2. Identifiers: Identifiers are programmer designed tokens. They are used for naming classess,
methods, variables, objects, packages and interfaces in a program.
Thumb Rules: These are the rules to be followed when declaring identifiers.
 An identifier can have alphabets, digits and underscore and dollar-sign characters.
 They must not begin with a digit.
 Java is case-sensitive (uppercase & lowercase letters are distinct), so VALUE is a
different identifier than Value.
 Some examples of valid identifiers are:
Avg Temp count a4 $test this_is_ok
 Invalid variable names include: 2count high-temp Not/ok
3. Literals: A constant value in Java is created by using a literal representation of it. For
example, here are some literals:
 Integer literal: 100
 Real (Floating point) literal: 98.6
 Single character literal: ‘X’
 String literal: “This is a test”
 Boolean literal: true (or) false
4. Operators: An operator is a symbol that takes one or more arguments and operates on them
to produce a result.
5. Separators: In Java, there are a few characters that are used as separators. These are used to
indicate where group of code are divided and arranged. The most commonly used separator in
Java is the semicolon.
Symbol Name Purpose
Used to enclose parameters in method definition.
() Parenthesis
. Used to define a block of code for classes and methods.
{} Braces

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 15


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Used to declare array types.


[] Brackets
Used to separate and terminate the statements.
; Semicolon
Used to separate consecutive identifiers in a variable
, Comma declaration.
Used to separate package names from sub packages and classes.
. Period Also used to separate a variable or method from a reference
variable.

6. Java Keywords: There are 50 reserved keywords currently defined in the Java language.
 Keywords have specific meaning in Java
 These keywords cannot be used as names for a variable, Class or method.
 All the keywords are to be written in lower-case letters.
Java keywords are:
abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while

Constants, Variables and Data Types


Constants:
A programming language is designed to process certain kinds of data containing of
numbers, characters and strings and provide useful output known as information.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 16


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Constants in java refer to fixed values that do not change its value during the execution of
a program. Java supports several types of constants they are
JAVA Constants

Numeric Constants Character Constants Boolean Constants

Integer Constants Real Constants Character Constants String Constants


Integer constants: An integer constant refers to a sequence of digits. There are three types of
integers namely, decimal integer, octal integer and hexadecimal integer.
Decimal integer consists of a set of digits, 0 through 9, preceded by an optional minus
sign. Examples of decimal integer constants are:
123 -321 0 654321
An octal integer constant consists of any combination of digits from the set 0 through 7,
with a leading 0. Some examples of octal integers are:
037 0 0435 0551
A sequence of digits preceded by “0X” is considered as hexadecimal integer. They are
also including alphabets from “A” to “F”. a letter ‘A’ to ‘F’ represents the number 10 to 15 .
Following are the examples of hexadecimal integers:
0X2 0X9F 0Xbcd 0X
Real Constants: Real (Float) constants are the numbers followed by fractional part.
Example for real or floating constants: 0.0083 -0.45 435.65 215.65
Real numbers may also be expressed in exponential notations. For example the value
215.65 may be written as 2.1565e2. e2 means multiply by 102. The general form is
Mantissa e exponent
Mantissa means real number expression
256.85 written as 2.5685e2

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 17


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Here 2.568 mantissa


e symbol of exponential
2 exponent

Single character constant: A single character constant contains a single character enclosed
with in a pair of single quote marks. Examples of character constants are:
‘5’ ‘X’ ‘;’ ‘ ’
The character constant ‘5’ is not same as the number 5. The last constant is blank space.
String Constants: A string constant is a sequence of characters enclosed between double
quotes. The characters may be alphabets, digits, special characters and blank spaces.
Examples of string constants: “Hello java”, “1992”, “14+12”, “...” , “ ”
Boolean constants: Boolean constants are true and false. Java does not use integers to represent
true or false.
Example: boolean x= true;
Backslash character constants: These are used in output methods. These characters are also
known as escape sequences. These constants are given below.
Constant Meaning
\b backspace
\f form feed
\n new line
\r carriage return
\t horizontal tab
\’ single quote
\” double quote
\\ back slash

Variables
A variable is an identifier that denotes a storage location used to store a constant value.
Unlike constants, a variable may take different values in different times during the execution of
a program. A variable name can be chosen by the programmer in a meaningful way.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 18
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Example: average, height, total_marks.


A variable name may consist of alphabets, digits, the underscore ( _ ) and dollar ($)
characters subject to the following conditions.
 They must not begin with a digit.
 Uppercase and lower case names are different. This means that the variable Total is not
the same as total or TOTAL.
 It should not be a keyword
 White spaces are not allowed
 They can be of any length.

Scope of variables: Scope of a variable determines the area in which a variable can be
accessed. Java variables are actually classified into three types.
1. Instance variables
2. Class variables
3. Local variables
Instance variables: These are declared inside the class and these are created when the objects are
instantiated. They take different values for each object.
Class variables: These are also declared inside the class and are global to the class. And belongs
to the entire set of objects the class creates. They take common value for all the objects.
Local variables: Variables declared and used inside methods are called local variables. These
variables are not available for use outside the method definition. Local variables can also be
declared inside program blocks that are defined between an opening brace {and closing brace}.

Data Types
Every variable in java has a data type. Data type specifies the size and type of
values that can be stored into a variable. Java language is rich in data types. Data types in Java
under various categories are shown below.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 19


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Data types in Java

Primitive (Intrinsic) Non-Primitive


(Derived)

Numeric Non-Numeric Classes


Interfaces
Integer Character Arrays
Float Boolean
Integer type: Integer types can hold whole numbers (Integer constants) such as 123, -96 and
5639. Java supports four types of Integer data types. They are: byte, short, int and long.
Integer

Byte Long

Short Int

The below table shows the memory size and range of all four integer data types.
Type Size Minimum value Maximum value
byte 1 byte -128 127
short 2 bytes -32,768 32,767
int 4 bytes –2,147,483,648 2,147,483,647
long 8 bytes –9,223,372,036,854,775,808 9,223,372,036,854,775,807

Floating-Point Type: Floating-point numbers, also known as real numbers, are used when
evaluating expressions that require fractional precision. There are two kinds of floating-point
types: float and double, which represent single and double-precision numbers respectively.
Floating point data types supports a special value known as Not-a-Number (NaN) for
undefined numbers like zero by zero etc.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 20


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Type size Minimum value Maximum value


Float 4 bytes 3.4e-038 3.4e+038
Double 8 bytes 1.7e-308 1.7e+308

Character Data type: In Java, the data type used to store characters is char. char in Java is
not the same as char in C or C++. Java uses Unicode to represent characters. Unicode defines a
fully international character set that can represent all of the characters found in all human
languages.
It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic,
Hebrew, Katakana, Hangul, and many more. For this purpose, it requires 2 bytes.
Boolean type: Java has a simple type, called Boolean for logical values. It can have only one of
two possible values, true or false. It is used when we want to test a particular condition during
the execution of a program.
Declaration of variables: Variables are the names of storage locations. After designing suitable
variable names, we must declare them to the compiler. Declaration does three things:
1. It tells the compiler what the variable name is?
2. It specifies what type of data the variable will hold?
3. The place of declaration decides the scope of a variable.
Syntax: Data type variable1, variable2, variable3, ……… variableN;
Example: int count;
float x, y;

 Java program structure


A Java program may contain many classes of which only one class define main
method. Classes contain data members and methods that operate on the data members of the
class. Methods may contain data type declarations and executable statements. To write a java
program, we first define classes and then put them together. A java program may contain one or
more sections.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 21
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Documentation section
Suggested
Package statement Optional
Import statement Optional
Interface statement Optional
Class definitions
Optional
Main method class
{
Main method definition
Essential
}
Fig : General Structure of a java program
Documentation section: The documentation section comprises a set of comment lines giving
the name of the program, the author and other details, which the programmer would like to refer
to at a later stage.
1) Single line comments: //…………..
2) Multi line comments: /* …………*/ and /** …………. */
Package Statement: The first statement allowed in a java file is a package statement. This
statement declares a package name and informs the compiler that the classes define here belong
to this package.
Example: package student;
Import statement: The next thing after a package statement may be a number of import
statements. This similar to the #include statements in C
Example: import java.io.*;
Interface Statements: An interface is like a class but includes group of method declarations.
This is also an optional section and is used only when we wish to implement the multiple
inheritance features in the program. Interface is a new concept in java.
Class Definitions: A java program may contain multiple class definitions. Classes are the
primary and essential elements of java program. These classes are used to map the objects of
real-world problems.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 22


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Main Method Class: Every java stand-alone program requires a main method as its starting
point; this class is the essential part of java program. The main method creates objects of
various classes and establishes communications between them. On reaching the end of main,
the program terminates and control passes back to the operating system.
Simple Java Program:
/* this is a simple Java program */
class Simple
{
public static void main (String args[ ] )
{
System.out.println (" ****** This is my first Java program******");
}
}
Save it as: Simple.java
Compilation: javac Simple.java
Execution: java Simple
Output: ******This is my first Java program******

Class declaration: The first line of the above program class Simple declares a class, which is
an object-oriented construct. class is a keyword and declares that a new class definition follows.
Simple is a java identifier that specifies the name of the class to be defined.
Opening Brace: Every class definition in java begin with an opening brace “ { “ and ends with
matching closing brace } , appearing in the last line in the example. This is similar to C++ class
construct.
The Main Line: The third line of the above program public static void main(String args[ ])
define a method named main . Every java program must include the main( ) method. This line
contains keywords, public, static and void.
public The keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all over classes.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 23


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

static The keyword static, which declares this method as one that, belongs to the
entire class and not a part of any objects of class. The main must always be
declared as static since the interpreter uses this method before any objects
are created.
void The type modifier void states that the main method does not return any
value, but simply prints some text to the screen.

String args[ ] declares parameters named args, which contains an array of objects of the
class type “String”.
The output statement: The only executable statement in the program is
System.out.println(“****** This is my first java program ******”);
This is similar to printf( ) statement of C. In the above statement println( ) method is a
member of the out object, which is static data member of System class.

Implementing Java Program


Implementation of java application program involves a series of steps. They include.
 Creating the program
 Compiling program
 Running the program
Creating the program: We can create a program using any text editor like Notepad. Assume
that we have entered the following program
import java.io.*;
class Test
{
public static void main(String args[ ])
{
System.out.println(“Welcome to the world of java”);
System.out.println(“Let us learn java”);
}
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 24
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

We must save this program in a file called Test.java ensuring the file name contains the
class name properly. This file called source file. Note that all java source files will have the
extension of “.java”.
Compiling the program: To compile the program, execute the compiler javac, specifying the
name of the source file on the command line, as shown below:
C:\> javac Test.java
If everything is ok, the javac compiler creates a file called Test.class that contains the
byte code version of the program. The Java byte code is the intermediate representation of your
program that contains instructions the Java interpreter will execute.
Running the program: To actually run the program, we must use the Java interpreter called
java. To do so, pass the class name as a command-line argument, as shown here:
C:\>java Test
Now, the interpreter looks for main method in the program and begins execution from
there and produces the output.
Output: Welcome to the world of java
Let us learn java
Source Code

Java Compiler

Byte Code

Windows interpreter Unix interpreter Linux interpreter

Machine code Machine code Machine code

Windows computer Unix computer Linux computer

Fig: Implementation of java program


Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 25
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Giving values to variables: A variable must be given a value after it has been declared but
before it is used in an expression. It is of two types.
1. By using an assignment statement
2. By using a read statement.
By using an assignment statement: A simple method of giving value to a variable is through
the assignment statement as follows.
VariableName= value;
Example: count=100;
X=255.5;
It is also possible to assign a value to a variable at the time of declaration. This process of
giving initial values to variables is known as initialization.
Datatype variablename= value;
Example: int x=10;
By using a read statement: We may also give values to variables interactively through the
keyboard using the readLine( ) method.
Example: // program to read data from the keyboard interactively
import java.io.*
class Addition
{
public static void main(String args[ ])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int a, b, c;
System.out.println(“Enter two values”); The interactive input and output of the
a= Integer.parseInt(dis.readLine( )); above program is:
b= Integer.parseInt(dis.readLine( ));
Enter two values
c= a+ b;
10
System.out.println(“Sum=”+c);
20
}
Sum=30
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 26


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Getting values of variables: A computer program is written to manipulate a given set of data
and to display or print the results. Java supports two output methods that can be used to send the
results to the screen.
 print( ) method // print and wait
 println( ) method // print a line and move to next line
Standard default values: In Java, every variable has a default value. If we don’t initialize a
variable when it is first created, Java provides default value to that variable type automatically
as shown in below table:
Type of variable Default value
byte zero: (byte) 0
short zero: (short) 0
int zero: 0
long zero: 0L
float 0.0f
double 0.0d
char null-character
boolean false
reference null

 Naming conventions in Java: Naming conventions are the set of rules to be followed to
give names to the variables, classes and other tokens of a Java program. It is a better
programming practice to follow the naming conventions. The following are the rules suggested
in Java.
 Package names in Java are written in all small letters.
Example: java.io, java.awt, java.lang, …..
 Each word of a class name and interface name starts with a capital letter.
Example: String, DataInputStream, ….
 Method names starts with small letter, then each word that follows starts with a capital
letter.
Example: readLine( ), parseInt( ), …..

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 27


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

 Variable names also follow the above rules as methods, words may be separated by
underscore ( _ ).
Example: age, empName, emp_Sal, …..
 Constants should be written using all capital letters, words are separated by underscore.
Example: PI, MAX_VALUE, …
 All the key words should be written in all small letters.
Example: public, static, void, int, float, ….

Q: What is an operator? And what are the operators in Java?


A: An operator is a symbol that performs a specific operation on operands. Operands may be
variables or constants on which the operator performs operation.
Ex: int a=10, c;
C=a+20; here, a, 20 are operands, + is an operator.
In Java operators can be classified into number of related categories as below:
i) Arithmetic operators
ii) Relational operators
iii) Logical operators
iv) Assignment operators
v) Increment and Decrement operators
vi) Conditional operators
vii) Bitwise operators
viii) Special operators
Arithmetic Operators: Arithmetic operators are used to construct mathematical expressions as
in algebra. Java provides all the basic arithmetic operators.
Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division (quotient)
% modulo division (remainder)

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 28


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Integer Arithmetic: An arithmetic operation involves only integer operands is called integer
arithmetic.
Example: 10+20=30, here 10, 20 are integers.
Real Arithmetic: An arithmetic operation involves only real operands is called real arithmetic.
Example: a=20.5, b=6.4; => a+b= 26.9. Here, a & b are real operands.
Mixed mode Arithmetic: When one operand is real and other is integer then that expression is
called mixed mode arithmetic.
Example: 15/10.0=1.5. here, 15 is integer and 10.0 is real operand.
// Example program for Arithmetic operators.
import java.io.*
class Arith
{
public static void main(String args[ ])throws IOException
{
DataInputStream dis= new DataInputStream(System.in);
int a,b;
System.out.println(“Enter two numbers”);
a=Integer.parseInt(dis.readLine( ));
b=Integer.parseInt(dis.readLine( ));
System.out.println(“Addition=”+(a+b));
System.out.println(“Subtraction=”+(a-b));
System.out.println(“Multiplication=”+(a*b));
System.out.println(“Quotient=”+(a/b));
System.out.println(“Remainder=”+(a%b));
}
}
The output of the program is as follows:
Enter two numbers
20
3
Addition=23
Subtraction=17
Multiplication=60
Quotient=6
Remainder=2
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 29
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Relational operators: These operators are used to compare two quantities depending on their
relation. An expression containing relational operators is called as relational expression.
Operator Meaning
== Equal to
!= not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Example: 4.5<=10 is TRUE
-35>=0 is FALSE
//Example program on Relational operators
import java.io.*;
class Relation
{
public static void main(String args[ ])throws IOException
{
float a=15.0F, b=20.75F, c=15.0F;
System.out.println(“a<b is”+(a<b));
System.out.println(“a>b is”+(a>b));
System.out.println(“a= =c is”+(a= =c));
System.out.println(“a<=c is”+(a<=c));
System.out.println(“a>=b is”+(a>=b));
System.out.println(“b!=c is”+(b!=c));
}
}
The output of above program is:

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 30


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

a<b is true
a>b is false
a= =c is true
a<=c is true
a>=b is false
b!=c is true
Logical operators: In addition to the relational operators, Java has three logical operators.
Which are given below:
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
These operators are used to form compound conditions by combining two or more
relations.
Example: a>b && x= =10
Like the simple relational operators, a logical operator also returns either true or false.
Truth table:
Op-1 Op-2 Op-1 && Op-2 Op-1 || Op-2
True True True True
True False False True
False True False True
False False False False
Assignment operators: Assignment operators are used to assign the value of an expression to a
variable. The usual assignment operator is ‘=’. In addition, Java has a set of shorthand
assignment operators which are used in the form

V Op = Exp;

Where, V is a variable, op is a Java binary operator and exp is an expression (value).


V op=exp; is equivalent to V=V op(exp);
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 31
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Example: x + = 3 is equal to x = x + 3.
Statement with shorthand assignment operator Statement with simple assignment operator

a+ =1 a=a+1
a - =1 a=a–1
a* =1 a=a*1
a/ =b a=a/b
a% =b a = a% b
Shorthand assignment operators have three advantages.
i) It is easier to write the expression
ii) The statement is more concise and easier to read.
iii) Use of shorthand operator results in a more efficient code.
Increment and Decrement operators:
Increment operator(++): It increments the value of variable by 1 on which it is operating.
There are two types of increment operators. I) pre increment II) post increment.
i) Pre increment operator: It first increment the operand and then the result is assigned to the
variable on the left.
Ex: int x=3, y;
y= ++x;
In the above statement: x value becomes 4 and y takes 4.
ii) Post increment operator: It first assigns the value to the variable on the left and then
increment the operand.
Ex: int x=3, y;
y= x++;
In the above statement: x value becomes 4 but y takes 3.
Decrement operator(- -): It decrements the value of variable by 1 on which it is operating.
There are two types of decrement operators. I) pre decrement II) post decrement.
iii) Pre decrement operator: It first decrement the operand and then the result is assigned to the
variable on the left.
Ex: int x=3, y;

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 32


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

y= - -x;
In the above statement: x=2, y=2
iv) Post decrement operator: It first assigns the value to the variable on the left and then
decrement the operand.
Ex: int x=3, y;
y= x- -;
In the above statement: x=2 but y=3.
Conditional operator: The character pair ?: is the conditional operator. It is also called as
ternary operator because it is used on three operands. The general syntax of the conditional
operator is: exp1 ? exp2 : exp3
The conditional operator works as follows: exp1 is evaluated first, if it is true exp2 is
evaluated and its value becomes the value of expression. If exp1 is false exp3 is evaluated and
its value becomes the value of expression.
Ex: int a=10, b=20, big;
big= (a>b)? a : b;
System.out.println(big); // prints 20

Bitwise operators: Bitwise operators are used to perform operations on bits(0 and 1). They
convert the numbers into binary system and then apply bitwise operators. Bitwise operators may
not be applied to float or double.
Operator Name
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< left shift operator
>> right shift operator
~ complement operator
>>> right shift with zero fill
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 33
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Bitwise AND(&): It returns 1, when both bits are 1’s otherwise 0.


Ex: x = 1101
y = 1001
x & y= 1001

Bitwise OR(|): It returns 1, when both or any one of two bits is 1 otherwise 0.
Ex: x = 1101
y = 1001
x | y= 1101

Bitwise XOR(^): It returns 1, only if one of the bits is 1 otherwise 0.


Ex: x = 1101
y = 1001
x ^ y= 0100

Left shift operator(<<); It moves the bits towards leftside and 0’s are added from rigrt.
Ex: x = 0000 0000 1011 1101
x<<3 = 0000 0101 1110 1000
Right shift operator(>>): It moves the bits towards right an 0’s are added from left.
Ex: x = 0000 0000 1011 1101
x>>3 = 0000 0000 0001 0111

Right shift with zero fill: When dealing with positive numbers there is no difference between
>> and >>>. When dealing with negative numbers, the >>> operator shifts zeros into all the
upper bits, including high order bit, thus making a negative number into positive.

Complement(~): It converts 0’s into 1’s and 1’s into 0’s.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 34


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Ex: x = 0000 0000 0000 1011


~x= 1111 1111 1111 0100
Truth table:
A B A&B A|B A^B
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0

Special operators: Java supports some special operators. They are:


i) instanceof operator
ii) member selection operator (.)
instanceof operator: It returns true, if the object on the left hand side is an instance of the class
given on the right hand side.
Example: student instanceof person;
Is true if the object student belongs to the class person, otherwise false.
(.) dot operator: It is used to access the instance variables and methods of class objects.
Example: person1.age; // Reference to the variable age
person1.salary( ); // Reference to the method salary( ).
It also used to access classes and sub packages from a package.

Q: Explain control structures in JAVA.


A: Normally statements in JAVA program are executed sequentially i.e. in the order in
which they are written. This is called Sequential execution. Transfering control to a desired
location in a program is possible through control structure. JAVA allows many kind of control
structures, which include:
I) Conditional control structure ( Decision making with Branching statements)
i) if
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 35
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

ii) if…else
iii) nested if….else
iv) else….if ladder
v) switch
II) Looping control structures ( Decision making and Looping (or) Iterative statements)
i) While loop
ii) do while loop
iii) for loop
iv) for each(enhanced for) loop
III) Jumping control Structures
i) break
ii) labelled break
iii) continue
iv) labelled continue
Decision making and Branching statements (or) Conditional control structures:
Branching: When a program breaks the sequential flow and jumps to another part of code is
called as branching.
i) if: The if structure is also called as conditional statement. If the “test expression” is true then
statement-block will be executed. Otherwise the statement-block is skipped and the
execution will jump to the statement-x.
Syntax: Flowchart: entry

test
if( test expression) expression true
?
{
Statement-block
Statement-block; false
}
Statement-x; Statement-x
false

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 36


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

//Example program to find the given number is positive or not


import java.io.*;
class Simple
{
public static void main(String args[ ])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int x;
System.out.println(“Enter a number”);
x= Integer.parseInt(dis.readLine( )); Input and output of program is:
if(x>0) Enter a number
{ 15
15 is positive number
System.out.println(x+”is positive number”);
Program end
}
System.out.println(“Program end”);
}
}
ii) if…else: This statement is an extension of simple if statement
Syntax: Flow chart: entry
if (test expression)
{ True False
test
True-block statements; expression
} ?
else
{
False-block statements; True block False block
} statements statements
statement-x;
Statement-x

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 37


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

In this type of statement if the test expression is true then the “true-block statements” will
be executed. Otherwise “false-block” statements will be executed.

//Example program to find biggest among two numbers


import java.io.*;
class Big
{
public static void main(String args[ ])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int x, y;
System.out.println(“Enter two integer numbers”);
x= Integer.parseInt(dis.readLine( )); Input and output of program is:
y= Integer.parseInt(dis.readLine( )); Enter two integer numbers
if(x>y) 25
58
System.out.println(x+”is big number”);
58 is big number
else
System.out.println(y+“is big number”);
}
}

iii) Nested if…else: Writing of if…else statement in another if or else statement is called as
Nested if…else.
In this, if the condition1 is false statement-3 will be executed; otherwise it continues to
perform condition2. If condition2 is true statement-1 will be executed. Otherwise statement-
2 will be executed and then control is transferred to statement-x.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 38


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Syntax: Flowchart:
if(condition1) false true
{ Condition1
if(condition2) ?
{ Statement-1; }
Statement-3
else false true
{ statement-2; } Condition2
} ?
else
{ Statement-2 Statement-1
Statement-3;
}
Statement-x;

Statement-x

//Example program to determine the largest of three given numbers


import java.io.*;
class Largest
{
public static void main(String args[ ])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int a, b, c;
System.out.println(“Enter three integer numbers”);
a= Integer.parseInt(dis.readLine( )); Input and output of program is:
b= Integer.parseInt(dis.readLine( )); Enter three integer numbers
c= Integer.parseInt(dis.readLine( )); 25
58
if(a>b)
45
{
Largest value is=58
if(a>c)
System.out.println(“Largest value is=”+a);
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 39
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

else
System.out.println(“Largest value is=”+c);
}
else
{
if(b>c)
System.out.println(“Largest value is=”+b);
else
System.out.println(“Largest value is=”+c);
}
}
}
iv) else…if ladder: There is another way of putting ifs together when multipath decisions are
involved.
Syntax: if(condition1)
statement-1;
else if(condition2)
statement-2;
else if(condition3)
statement-3;
:
:
else if(condition n)
statement-n;
else
default-statement;
statement-x;

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 40


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

This construct is known as else…if ladder. The conditions are evaluated from the top to
downwards. As soon as the true condition is found, the statement associated with it is executed
and the control is transferred to the statement-x. When all the ‘n’ conditions become false, then
the final else containing the default-statement will be executed.

v)
Flow chart:

Entry

True False
Condition1
?
True False
Statement-1 Condition2
?

True False
Statement-2 Condition3
?

True False
Statement-3
Condition n
?

Statement-n default-statement

Statement-x

//Example program to determine the largest of three given numbers


import java.io.*;
class Largest
{

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 41


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

public static void main(String args[ ])throws IOException


{
DataInputStream dis=new DataInputStream(System.in);
int a, b, c;
System.out.println(“Enter three integer numbers”);
a= Integer.parseInt(dis.readLine( )); Input and output of program is:
b= Integer.parseInt(dis.readLine( )); Enter three integer numbers
c= Integer.parseInt(dis.readLine( )); 25
58
if(a>b && a>c)
45
System.out.println(“Largest value is=”+a);
Largest value is=58
else if(b>c)
System.out.println(“Largest value is=”+b);
else
System.out.println(“Largest value is=”+c);
}
}
vi) switch: It is called as multi-way conditional control structure. The switch statement tests the
value of a given variable (or expression) against a list of case values and when a match is
found, a block of statements associated with that case is executed. The general form of
switch statement is:
Syntax: switch( expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 42


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

break;
:
:
default:
default-block;
break;
}
Statement-x;
The “expression” is an expression or characters. Value-1, value-2,….. are the constants
and are known as case labels.
Flow chart:
Entry

expression

expression=value-1 block-1

expression=value-2
block-2

:
(no match found) default
default-block

Statement-x

//Example program to display the name of the day depending on the number entered from
keyboard.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 43


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

import java.io.*;
class Days
{
public static void main(String args[ ])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int day;
System.out.println(“Enter a number between (1-7)”);
day=Integer.parseInt(dis.readLine( ));
switch(day)
{
case 1: System.out.println(“”Monday”);
break;
case 2: System.out.println(“Tuesday”);
break;
case 3: System.out.println(“Wednesday”);
break;
case 4: System.out.println(“Thursday”); The output of the program is:
break; Enter a number between (1-7)
case 5: System.out.println(“Friday”);
2
break;
Tuesday
case 6: System.out.println(“Saturday”);
break;
case 7: System.out.println(“Sunday”);
break;
default: System.out.println(“Number not valid”);
break;
}
}
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 44
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Looping control structures ( Iterative control structures):


The process of repeatedly executing a block of statements is known as looping. In
looping, sequences of statements are executed until some conditions for the termination of the
loop are satisfied. A program loop therefore consists of two segments.
i) Body of the loop
ii) Control statement
Depending on the position of the control statement in the loop, a control structure may be
classified into:
i) Entry controlled loop
ii) Exit controlled loop
Entry Entry

Test Body of the


False
Condition Loop

True
Body of the
Test True
Loop
Condition

False

a) Entry controlled loop b) Exit controlled loop


Ex: while, for Ex: do-while

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 45


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

In the Entry controlled loop, the conditions are tested before the start of the loop
execution. If the conditions are not satisfied then the body of the loop will not be executed.
In the Exit controlled loop, the test is performed at the end of the body of the loop and
therefore the body of the loop is executed unconditionally for the first time.
A looping process would include following four steps:
i) Setting and initialization of a counter
ii) Test for a specified condition for execution of the loop
iii) Execution of the statements in the loop
iv) Increment the counter.

While loop: The basic form of the while statement is:


Initialization;
while(test condition)
{ True Body of the loop
condition
Body of the loop
} False

The while is an Entry controlled loop statement. The test condition is evaluated and is the
condition is true then the body of the loop is executed. After execution of the body, the
condition is once again evaluated and if it is true, the body is executed once again. This process
of repeated execution of body continues until the condition is false.
// Example program to print 1 to 10 numbers
class Printing
{
public static void main(String args[ ])
{
int i=1;

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 46


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

while(i<=10)
{
System.out.println(i);
i++;
}
}
}

do-while loop: It is an Exit controlled loop statement. In some situations it may be necessary to
execute the body of the loop before the test is performed. Such situations can be handled with
the help of do-while statement. The basic form of do-while statement is:
Initialization;
do True
{
Body of the loop Condition
Body of the loop
} while(condition); False

On reaching the do statement, the program proceeds to evaluate the body of the loop first.
At the end of the loop, the condition is evaluated. If the condition is true once again the body of
the loop is executed. This process continues until the condition becomes false.
// Example program to find the sum of natural numbers.
import java.io.*;
class Natural
{
public static void main(String args[ ])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 47


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

int n, i=1, sum=0;


Output of the program is:
System.out.println(“Enter range”);
Enter range
n=Integer.parseInt(dis.readLine( ));
10
do
Sum of 10 natural numbers is 55
{
sum= sum+ i;
i++;
}while(i < = n);
System.out.println(“sum of” + n + ”natural numbers is”+sum);
}
}

for loop: The for loop is another entry controlled loop, this provide a more concise loop
structure. The basic form of the loop is:
for (initialization ; condition ; increment/decrement)
{
Body of the loop
}

initialization

True
Condition Body of the loop Increment/decrement

False

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 48


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

The execution of for loop is as follows:


1. Initialization of control variable is done first, using the assignment statements.
Ex: int i=0, count=1,…. Etc.
2. The value of control variable is tested using the condition. If the condition is true, the
body of the loop is executed, otherwise the loop is terminated.
3. When the body of the loop is executed, the control is transferred back to the for
statement. Now the variable is incremented (or decremented) and the new value of
control variable is again tested using the condition. This process continues until the
condition becomes false.

// Example program to find factorial of a given number.


import java.io.*;
class Fact
{
public static void main(String args[ ])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int n, i, fact=1;
System.out.println(“Enter a number”); Output of the program is:
n=Integer.parseInt(dis.readLine( )); Enter a number
for(i=1; i<=n; i++) 5
{ Factorial of 5 is 120
fact= fact * i;
}
System.out.println(“Factorial of “+n+”is”+fact);
}
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 49


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

for each (enhanced for) loop: The enhanced for loop is also called as for each loop. It is
introduced in J2SE 5.0. This is more used with arrays and enumerations. Generally to access
array elements, we use indexes. But using for each, we can directly access each element of the
array without indexes. The basic form of for each loop is:
for (variable: Expression)
{
Statements
}
Example: int x[ ]= {10, 20, 30};
for (int k : x)
System.out.print(k+” “);
The above code prints: 10 20 30.

Nested loops:
If a loop is combined in another loop, it is said to be a nested loop. In a nested loop, the
inner loop gets executed for each iteration of the outer loop. Commonly a “for loop” takes
another for loop within.
Example: Generally to print a double dimensional array we use nested for loop.
Ex: int a[ ][ ]={ {1,2,3}, {4,5,6}, {7,8,9} };
for (int i=0; i<3; i++)
{
System.out.println(“ “);
for(int j=0; j<3; j++)
{
System.out.println(“\t”+ a[i][j]);
}
}
In the above program ‘j’ takes values from 0 to 2 for each iteration of outer loop.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 50
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Jumping control structures:


break: An early exit from a loop can be accomplished by using the break statement. We can
use break in switch statement, while, do and for loops.
When the break statement is encountered in a loop, the loop is immediately exited and
program continues with the statement immediately following the loop.
Syntax: break;
Example: for(int i=1; i<=10; i++)
{
System.out.println(“Hello”);
if(i = =5)
break;
}
The above code prints “Hello” for 5 times only.

Labeled break: We can give a label to a block of statements. A label is any valid Java variable
name. To give a label to a loop, place it before the loop with a colon at the end.
Example: Outer: for(int i=1; i<=10; i++)
{
System.out.println(“Hi”);
for(int j=1; j<=10; j++)
{ Output:
System.out.println(“Hello”); Hi
Hello
if( j= =2) Hello
break Outer;
}
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 51


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Continue: It may be necessary to skip a part of the body of the loop under certain conditions.
This can be possible by using continue statement.
Syntax: continue;
Example: class ContDemo
{
public static void main(String args[ ])
{
for(int i=1; i<=5; i++)
{
if(i= =3)
continue;
System.out.print(i);
}
}
}
The above code prints 1 2 4 5. It means 3rd iteration is skipped.

Labeled continue: If we want to jump outside a nested loop or to continue a loop that is outside
the current one, then we use the labeled continue statement.
Example: Outer: for(int i=1; i<11; i++)
{
for(int j=1; j<11; j++)
{
System.out.println(“ ”+(i*j));
if( i= =j)
continue Outer;
}
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 52


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Q: What is a class? And explain about defining a class, creating objects and accessing
class members with examples.
A: A class is a template, blueprint,or contract that defines what an object’s data fields and
methods will be. An object is an instance of a class. You can create many instances of a class. A
Java class uses variables to define data fields and methods to define actions.
A class in Java can be created by using the keyword “class”.
Defining a class:
class classname [extends superclass name]
{
[fields declarations;]
[methods declarations;]
}
In the above syntax “classname” is the name of the class. Everything inside the square
brackets is optional. This means that the following would be a valid class definition.
Example: class Empty
{
}
Because the body is empty, this class does not contain any properties and therefore
cannot do anything.
Fields declaration: It is similar to declaring local variables but they may have access modifiers
like public, private, static and etc.
Example: class Rectangle
{
int length;
int width;
}
These variables are also called as instance variables or member variables.
Methods declaration: A class with only data fields has no life. We must therefore add methods
that are necessary for manipulating the data. Methods are declared inside the body of the class,

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 53


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

but immediately after declaration of instance variables. The general format of a method
declaration is:
type methodname (Parameter_List)
{
Method_body;
}
Method declaration has four parts.
i) The name of the method (methodname)
ii) The type of the value the method returns (type)
iii) A list of parameters (Parameter_List)
iv) The body of the method.
Example: class Rectangle
{
int length;
int width;
void getData (int x, int y)
{
length=x;
width=y;
}
}
If a method does not return any value then the return type is “void”.

Creating objects: Objects in Java are created using the “new” operator. The new operator
creates an object of the specified class and returns a reference to that object.
Syntax: classname objectname= new classname( );
Example: Rectangle rect1= new Rectangle( );

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 54


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Accessing class members: All variables must be assigned values before they are used. Since
we are outside the class, we cannot access the instance variables and the methods directly. To
do this, we must use the object and the dot operator.
Syntax: objectname. variablename= value;
objectname. methodname(parameterlist);
Example: rect1.length=10;
rect1.getData(10, 11);
Example: class Rectangle
{
int length;
int width;
void getData (int x, int y)
{
length=x;
width=y;
}
int rectArea( )
{
int area=length* width;
return(area);
}
}
class RectArea
{
public static void main(String args[ ])
{
int area1, area2;
Rectangle rect1=new Rectangle( );
Rectangle rect2=new Rectangle( );
rect1.length=15;
rect1.width=10;
area1=rect1.length*rect1.width; Output:
rect2.getData(20,12); Area1=150
area2=rect2.rectArea( );
System.out.println(“Area1=”+area1); Area2=240
System.out.println(“Area2=”+area2);
}
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 55
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Q: Explain Interfaces in Java?


A: An interface is basically a kind of class. Like classes interfaces contain methods and
variables but with a major difference. The difference is that interfaces define only abstract
methods and final fields. Therefore it is the responsibility of the class that implements an
interface to define the code for implementation of these methods.
 In an interface all methods are implicitly public.
 In an interface all variables are static and final.
 A class can implement many interfaces.
 Interface can be extended.
 It is not possible to create an object to an interface directly, but we can create reference
variables.
Interfaces are defined following syntax:
interface InterfaceName
{
Variable declarations;
Method declarations;
}

Here interface is the keyword and InterfaceName is any valid variable (just like class
name)
Example: interface Area
{
final static float pi=3.14f;
float compute(float x, float y);
}
Implementation of Interfaces: Interfaces are used as “super classes” whose properties are
inherited by classes. This is done as follows:
class classname implements interfacename
{
Body of class;
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 56
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Example program for calculating area of rectangle and circle using interfaces:
interface Area
{
final static float pi=3.14F;
float compute(float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return (x*y);
}
}
class Circle implements Area
{
public float compute(float x, float y)
{
return (pi*x*x); Output:
} Area of rectangle: 200
}
class InterfaceTest Area of circle: 314
{
public static void main(String args[ ])
{
Rectangle rect = new Rectangle( );
Circle cir = new Circle( );
Area a;
a= rect;
System.out.println(“Area of rectangle:” +a.compute(10,20));
a= cir;
System.out.println(“Area of circle:” +a.compute(10,0));
}
}

Q: How multiple Inheritance is achieved in java?


(OR)
Explain how to implement the concept of multiple inheritance using interfaces?

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 57


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

A: Java does not provide an explicit way to implement multiple inheritance i.e., a class can
never extend multiple classes. But this can be achieved using interfaces. This possible because
of two reasons
i) A class can implement multiple interfaces
ii) A class can simultaneously extend a class and implement one or more interfaces
The above forms are shown below:
1. interface A 2. class A
{……… {………
} }
interface B interface B
{……… {………
} }
class C implements A, B class C extends A implements B
{……… {………
} }
The following program illustrates how interfaces can be used to simulate multiple
inheritance. The program contains an interface named “Allowance” and classes named
“Employee” and “Salary”.
(Note: this program is also an example for accessing interface variables)
interface Allowance
{ interface class
int da=2000; Employee
Allowance
int hra=3000;
}
class Employee
{ Salary
private int empno;
private String name; class
public void getData(int eno, String n)
{
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 58
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

empno= eno;
name= n;
}
public void show( )
{
System.out.println(“Employee number:” +empno);
System.out.println(“Employee name:” +name);
}
}
class Salary extends Employee implements Allowance
{
private double sal;
Output:
public void getData(int eno, String n, double s)
{ Employee number: 7369
super.getData(eno, n); Employee name: Siri
sal= s;
} Total salary:25000
public void total( )
{
super.show( );
System.out.println(“Total salary:” +(sal+da+hra));
}
}
class Test
{
public static void main(String args[ ])
{
Salary e1= new Salary( );
e1.getData(7396,”Siri”,20000);
e1.total( );
}
}

Q: Explain Enumerated data types?


A: Enumerated data type is a type whose fields consist of a fixed set of constants. It is
something like defining words with constant values.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 59
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

J2SE 5.0 allows us to use the enumerated type in Java using the “enum” keyword. The
names of an enum type’s fields are generally written in uppercase letters, because they are
constants. Common examples include compass directions (NORTH, SOUTH, and EAST,
WEST) and days of week.
Advantages of using the enumerated type are:
 Compile time type safety.
 We can use the enum keyword in switch statement.
 Efficient.
Consider the following example it specifies a days_of_week using enum type:
Example:
class enumTest
{
enum Days{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRI DAY,SATURDAY};
public static void main(String args[ ])
{
for(Days d:Days.values( ))
System.out.println(d);
}
}
Q: Explain Object Oriented Paradigm. (OR) Object orientation.
A:
 The major factor in the invention of Object Oriented Approach is to overwrite some false
that are encountered in the Procedure oriented approach.
 OOP treats data as critical element in the program development and does not allow it to
move freely around the system.
 It tides data more closely to the functions that operate on it and protects it from accidental
modifications from outside functions.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 60
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

 OOP allows us to decompose (divide) a problem into a number of functions called as


“Objects”.
Object= Data + Methods
 The organization of data and functions (known as methods in JAVA) in OOP is shown
below.
Object A

Function

Data

Object B Object C
Function Function

Data Data

 Emphasis is on data rather than procedure.


 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through functions.
 New data and functions can be easily added whenever necessary.
 OOP follows bottom-up approach.

Q: Explain Encapsulation, Inheritance and Polymarphism.


A:
Encapsulation: The mechanism of combining the data and methods into a single unit (called
class) is known as Data encapsulation. Data encapsulation is the most striking feature of a class.
The data not accessible to the outside world and only those methods, which are wrapping in the
class, can access it. The insulation of the data from direct access by program is called Data
Hiding.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 61


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Example:
class Person
{
private int age;
private String name;
void setDetails(int a, String n)
{
age=a;
name=n;
}
void talk( )
{
System.out.println(“My name is:”+name);
System.out.println(“My age is:”+age);
}
}
In this example, we are providing security to the data members by using private keyword,
which means they can not be accessible by outside classes(i.e. Data Hiding).
Polymorphism: Polymorphism is another important OOPs concept. Polymorphism means the
ability to take more than one form. For example, an operation may exhibit different behaviors in
different instances (objects). The behavior depends upon the types of data used in the operation
Example: Consider the operation of addition for two numbers, the operation generates a
sum. If the operands are strings, then the operation would produce a third string by
concatenation Shape
Draw ( )

Circle object Box object Triangle object


Draw (circle) Draw (Box) Draw (Triangle)

The figure illustrates, that a single function name can be used to handle different number and
different type of arguments.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 62
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Java provides two ways to implement polymorphism.


1. Static Polymorphism (Compile time polymorphism/ Method overloading):
Two or more methods can have same names provided but the signature should be different,
i.e. different number of arguments or different types of arguments is called method overloading.
Example: class Calc
{
public void sum (int x, int y)
{
System.out.println(“Sum=”+(x+y));
}
public void sum (double x, double y)
{
System.out.println(“Sum=”+(x+y));
}
public void sum (int x, int y, int z)
{
System.out.println(“Sum=”+(x+y+z));
}
}
class MethOverLoad
{ Output:
public static void main(String args[ ])
{ Sum=29
Calc c1= new Calc( ); Sum=33.0
c1.sum(9, 20);
c1.sum(10.5, 22.5); Sum=40
c1.sum(9, 20, 11);
}
}
In the above example, we are using only one method (function) name but signatures are
different.
2. Dynamic Polymorphism (Run time polymorphism/ Method Overriding):
A method present in parent class and a method present in child class can have the same
names and same signatures, is called as method overriding. In this situation, the method of child
class is called with the objects of the child class.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 63


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Method overriding takes place only when a method with same signature in present in
both parent and child class.
Example: class One
{
public void show( )
{
System.out.println(“This is parent class”);
}
}
class Two extends One
{
public void show( )
{
System.out.println(“This is child class”);
} Output:
}
class Test This is child class
{ This is child class
public static void main(String args[ ])
{
Two t= new Two( );
t.show( );
t.show( );
}
}
Inheritance: Inheritance is the process by which objects of one class can acquire the properties
of objects of another class. (OR) The mechanism of deriving a new class from an old one is
called Inheritance. Inheritance supports the concept of hierarchical classification.
Inheritance provides the concept of reusability. This means that we can add additional
features to an existing class without modifying it. This is possible by deriving a new class
(child) from existing one (parent). The new class will have the combined features of both the
classes.
 Inheritance provides reusability of the code, which means to reuse something that already
exists rather than writing the same thing again.
 It allows modifiability without affecting the existing class.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 64
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

 It is used to arrange classes in hierarchical model.


 Inheritance allows subclasses to inherit all the variables and methods of their parent
classes.
Syntax of Defining a subclass: Parent class
class subclassname extends superclassname
{
Variable declarations; Inheritance
Method declarations;
Child class
}
The keyword “extends” indicates that the properties of superclassname are extended to
subclassname. The subclass will now contain its own variables and methods as well as its super
class members. Inheritance may take difference forms:
i) Single inheritance (only one super class)
ii) Multi level inheritance (Derived from a derived class)
iii) Hierarchical inheritance (One super class, many sub classes)
iv) Multiple inheritance (Several super classes)
v) Hybrid inheritance
Single Inheritance: If a class is derived from another class, it can be called as Single
Inheritance. A Base class
Syntax: class A
{
……
}
class B extends A
{ B
…… Derived class
}
Example: class Alpha
{
public void show( )
{
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 65
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

System.out.println(“Hello Alpha”);
}
}
class Beta extends Alpha
{
public void display( )
{
System.out.println(“Hello Beta”);
}
}
class SingleInh
{
public static void main(String args[ ]) Output:
{ Hello Alpha
Beta b1= new Beta( );
b1.show( ); Hello Beta
b1.display( );
}
}
Multi level Inheritance: If a class is derived from the class, which is derived from another
class, it can be called as Multi level inheritance. A Super class
Syntax: class A
{…..
}
class B extends A B Intermediate
{….. Super class
}
class C extends B
{….. C Sub class
}
Example:
class Alpha
{
public void show( )
{
System.out.println(“Hello Alpha”);
}
}
class Beta extends Alpha

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 66


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

{
public void display( )
{
System.out.println(“Hello Beta”);
}
}
class Gamma extends Beta
{
public void show2( )
{
System.out.println(“Hello Gamma”);
}
}
class MultiLevelInh
{
public static void main(String args[ ]) Output:
{ Hello Alpha
Gamma g= new Gamma( );
g.show( ); Hello Beta
g.display( ); Hello Gamma
g.show2( );
}
}

Hierarchical Inheritance: If two or more classes are derived from one super class is known as
Hierarchical Inheritance.
A
Syntax: class A
{…..
}
class B extends A
{…..
} B C D
class C extends A
{…..
}
class D extends A
{…..
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 67


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Example: class Alpha


{
public void show1( )
{
System.out.println(“Hello Alpha”);
}
}
class Beta extends Alpha
{
public void show2( )
{
System.out.println(“Hello Beta”);
}
}
class Gamma extends Alpha
{
public void show3( )
{
System.out.println(“Hello Gamma”);
}
}
class HierInh
{
public static void main(String args[ ]) Output:
{ Hello Alpha
Beta b1= new Beta( );
b1.show1( ); Hello Beta
b1.show2( ); Hello Alpha
Gamma g= new Gamma( );
g.show1( ); Hello Gamma
g.show3( );
}
}
Multiple Inheritance: If a class is derived from two or more super classes is known as multiple
inheritance. Java does not support this type of inheritance using classes.
A B

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 68


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Hybrid Inheritance: This is the combination of any two types of inheritances. Java does not
support this type of inheritance.

A Multi level inheritance

B D
Single inheritance

Q: What are Strings?


A: Strings represent sequence of characters enclosed in double quotation marks (“ ”). Java
provides a class named “String” to handle strings. The “String” class has several built-in
functions. Though String is a class, the instantiation of the objects need not be done using the
keyword “new”. Strings may be declared and created as follows:

String stringname;
stringname =new String(“string”);
The two statements may be combined as follows:
String stringname=new String(“string”);

Example: String name=new String(“sachin”);


 String can also be initialized as follows
String s1=”Delhi”;
 String objects are not mutable(self changeable)
 To find out string length we use “length( )” method of String class
Ex: int n=s1.length( );
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 69
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

The String class defines a number of methods that allows us to accomplish a variety of
string manipulation tasks.
Method call Task to be performed
s2=s1.toLowerCase( ) Converts the string s1 to all lower case
s2=s1.toUpperCase( ) Converts the string s1 to all Upper case
s2=s1.replace(‘X’, ’Y’) Replaces all appearances of X with Y
s2=s1.trim( ) Remove white spaces at beginning and end of string s1
s1.equals(s2) Returns true, if s1 is equal to s2
s1.equalsIgnoreCase(s2) Returns true, if s1=s2, ignoring the case
s1.length( ) Gives the length of s1
s1.charAt(n) Gives nth character of s1
s1.compareTo(s2) Return negative if s1 < s2
Positive if s1> s2
Zero if s1 is not equal to s2
s1.concat(s2) Concatenates s1 and s2
s1.substring(n) Gives substring starting from nth character
s1.substring(n, m) Gives substring starting from nth character to mth
character (not including mth)
String.valueOf(p) Creates a string object of the parameter p
p.toString( ) Creates a string representation of the object p
s1.indexOf(‘x’) Gives the position of the first occurrence of ‘x’
s1.indexOf(‘x’, n) Gives the position of ‘x’ that occurs after nth position
in the string s1.
(Note: Refer practical program no: 4)
Q: Write short notes on StringBuffer class?
A: StringBuffer is a peer class of String. While “String” creates strings of fixed length.
StringBuffer creates flexible length strings and that can be modified in terms of both length
and content. We can insert characters into or delete characters from a string.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 70


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

 String buffer objects are mutable(self changeable)


 It can be treated as dynamic string
String buffer can be initialized as follows”
StringBuffer s1=new StringBuffer(“abcd”);

Method Task
append( ) Used to concatenate the string in string buffer
insert( ) Used to insert any string at the specified position in the given string
reverse( ) Used to reverse the string present in string buffer
setCharAt( ) Used to set specified character in buffered string at specified position
delCharAt( ) Used to delete the specified character at a given position from the buffered
string
Example:
s1.append(s2) concatenates s1 & s2 strings
s1.insert(n,s2) inserts the string s2 at nth position of s1
s1.reverse( ) reverses the string s1
s1.setCharAt(n,’x’) modifies the nth character to x
s1.delCharAt(n) deletes the character at nth position of s1
(Note: Refer practical program no: 4)
Q: What is the difference between String and StringBuffer?
A: The differences between String and StringBuffer are listed below
 StringBuffer objects must be instantiated using “new” but String can also be instantiated
without using “new”.
 StringBuffer objects are mutable(self changeable). Whereas, String objects are
immutable.
 StringBuffer provides functions like setCharAt( ).delCharAt( ),etc.
 StringBuffer allocates extra 16 bytes of memory.
 StringBuffer can be treated as a dynamic string.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 71
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Q: What is an error? What are the various types of errors?


A: Errors are the wrongs that can make a program go wrong. In computer terminology errors
may be referred as “bugs”. It is common to make mistakes while developing as well as typing a
program. A misteke may lead to an error causing the program to produce unexpected result.
An error may produce an incorrect output or may terminate the execution of the program
abruptly(in middle) or even may cause the system to crash. Therefore it is important to detect
and manage properly all the possible errors.
Types of errors: Errors may broadly be classified into two categories:
i. Compile-time errors
ii. Run-time errors.
Compile time errors: All syntax errors will be detected and displayed by the java compiler and
therefore these errors are known as compile time errors. Whenever the compile displays an
error, it will not creat the “.class” file.
The most common errors are:
 Missing semicolons
 Missing brackets in classes and methods
 Misspelling of identifiers and keywords
 Missing double quotes in strings
 Use of undeclared variables
 Use of = in place of = = operator and so on.
Runtime errors: Some times, a program may compile successfully creating the “.class” file
but may not run properly. Such programs may produce wrong results due to wrong logic or may
terminate due to errors. Most common errors are:
 Dividing an integer by zero.
 Accessing an element that is out of bounds of an array.
 Trying to store a value into an array of an incompatible type.
 Attempting to use a negative size for an array.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 72


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

 Accessing a character that is out of bounds of a string.


 Converting invalid string to a number and so on.

Q: What are exceptions and exception handling? What are its advantages?
A: An exception is a condition that is caused by a run-time error in the program. When the
java interpreter encounters an error such as dividing an integer by zero, it creates an exception
object and throws it. If the exception object is not caught and handled properly, the interpreter
will display an error message and will terminate the program.
If we want the program to continue with the execution of the remaining code, then we
should try to catch the exception object thrown by the error condition and then display an
appropriate message for taking corrective actions. This is called as exception handling.
Advantages:
 It ensures safer termination of a program.
 User has a chance to correct the accidental mistakes while running a program.
 The program becomes robust and more user-friendly.
 It allows different handling code-blocks for different types of errors.

Q: What is exception handling? How do you perform exception handling in java?(OR)


Explain try-catch blocks (OR) Write syntax for handling exceptions in java?
A: Exception handling: Handling runtime errors is called as exception handling. When the
Java interpreter encounters an error, it creates an exception object and throws it (i.e. informs us
that an error has occurred).
If the exception object is not caught and handled properly the interpreter will display an
error message and will terminate the program. If we want the program to continue with the
execution of remaining code, then we should try to catch the exception.
The purpose of exception handling mechanism is to provide a means to detect and report
an “exceptional circumstance“, so that appropriate action can be taken. This mechanism
performs the following tasks.
1. Find the problem (Hit the exception).
2. Inform that an error has occurred (Throw the exception).
3. Receive the error information (Catch the exception).
4. Take corrective actions (Handle the exception).

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 73


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

The error handling code basically consists of two segments, one to detect errors and to
throw the exceptions and the other to catch exceptions and to take appropriate actions.
Exception handling mechanism includes following keyword: try, catch, throw, throws
and finally.
Syntax: try block
Statement that Exception object

Causes exception creator


Throws
Exception
Object

catch block Exception


statement that handler
handles the exception
try
{
Statements; //generates an exception
}
catch (Exception-Type1 a)
{
Statements; // processes the exception ‘a’
}
catch(Exception-Type2 b)
{
Statements; // processes the exception ‘b’
}
…….
…….
…….
finally
{
Statements to be executed before exiting exception handler
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 74


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

try block: “ try” block contains the code in which runtime error may occur. It throws Exception
object. A try block must be followed by at least one catch block or a finally block.
catch block: catch block contains the statements that are used to handle the runtime error. If the
catch parameter matches with the type of exception object, then the exception is caught and the
statements in that catch block will be executed. Otherwise, the exception is not caught and the
default exception handler will cause the execution to terminate.
finally block: the finally block is always executed, regardless of whether or not an exception is
thrown. Writing the finally block for try block is optional unless there is no catch block.
Example: class Error3
{
public static void main(String args[ ])
{
int a=10;
int b=5; Output:
int c=5;
int x, y;. Division by zero
try y=1
{
x=a/(b-c); //Exception here
}
catch(ArithmeticException e)
{
System.out.println(“Division by zero”);
}
y= a/(b+c);
System.out.println(“y=”+y);
}
}

Q: What is the dead_lock situation ?


A: Deadlock describes a situation, where two or more threads are blocked forever, waiting
for each other. This situation may occur when two or more threads are waiting to gain control
on a resource. But , Java automatically recognizes this situation and terminates some processes
automatically to ensure safer execution.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 75


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

UNIT-II
Q: What is an Algorithm? And how do you analyse it?
A: An algorithm is a step by step procedure to solve a problem. In normal language,
algorithm is defined as a sequence of statements which are used to perform a task. In computer
science, an algorithm can be defined as follows...
 An algorithm is a sequence of unambiguous instructions used for solving a problem,
which can be implemented (as a program) on a computer.
 Algorithms are used to convert our problem solution into step by step statements. These
statements can be converted into computer programming instructions which forms a
program. This program is executed by computer to produce solution. Here, program takes
required data as input, processes data according to the program instructions and finally
produces result as shown in the following picture.

Every algorithm must satisfy the following specifications...


1. Input - Every algorithm must take zero or more number of input values from external.
2. Output - Every algorithm must produce an output as result.
3. Definiteness - Every statement/instruction in an algorithm must be clear and
unambiguous (only one interpretation)
4. Finiteness - For all different cases, the algorithm must produce result within a finite
number of steps.
5. Effectiveness - Every instruction must be basic enough to be carried out and it also must
be feasible.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 76
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Example of Algorithm: Let us consider the following problem for finding the largest value in
a given list of values.
Problem Statement : Find the largest number in the given list of numbers?
Input : A list of positive integer numbers. (List must contain at least one number).
Output : The largest number in the given list of positive integer numbers.
Consider the given list of numbers as 'L' (input), and the largest number as 'max' (Output).
Algorithm:
 Step 1: Define a variable 'max' and initialize with '0'.
 Step 2: Compare first number (say 'x') in the list 'L' with 'max', if 'x' is larger than 'max',
set 'max' to 'x'.
 Step 3: Repeat step 2 for all numbers in the list 'L'.
 Step 4: Display the value of 'max' as a result.

Analysis of Algorithms: analysis of an algorithm is the process of calculating space required


by that algorithm and time required by that algorithm.
Performance analysis of an algorithm is performed by using the following measures...
1. Space required to complete the task of that algorithm (Space Complexity). It includes
program space and data space
2. Time required to complete the task of that algorithm (Time Complexity)
Space complexity:
When we design an algorithm to solve a problem, it needs some computer memory to
complete its execution. For any algorithm, memory is required for the following purposes...
1. Memory required to store program instructions
2. Memory required to store constant values
3. Memory required to store variable values
4. And for few other things
Space complexity of an algorithm can be defined as follows...

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 77


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Total amount of computer memory required by an algorithm to complete its execution is


called as space complexity of that algorithm
Generally, when a program is under execution it uses the computer memory for THREE
reasons. They are as follows...
1. Instruction Space: It is the amount of memory used to store compiled version of
instructions.
2. Environmental Stack: It is the amount of memory used to store information of partially
executed functions at the time of function call.
3. Data Space: It is the amount of memory used to store all the variables and constants.
Time complexity:
Every algorithm requires some amount of computer time to execute its instruction to
perform the task. This computer time required is called time complexity.
Time complexity of an algorithm can be defined as follows...
The time complexity of an algorithm is the total amount of time required by an algorithm
to complete its execution.
Generally, running time of an algorithm depends upon the following...
1. Whether it is running on Single processor machine or Multi processor machine.
2. Whether it is a 32 bit machine or 64 bit machine
3. Read and Write speed of the machine.
4. The time it takes to perform Arithmetic operations, logical operations, return value and
assignment operations etc.,
5. Input data.

Q: What is Pseudo code?


A: Pseudocode is an artificial and informal language that helps programmers to develop
algorithms. (OR) Pseudocode (pronounced SOO-doh-kohd) is a detailed yet readable
description of what a computer program or algorithm must do, expressed in a formally-styled
natural language rather than in a programming language.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 78
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Pseudocode is sometimes used as a detailed step in the process of developing a program.


Because pseudocode is detailed yet readable, it can be inspected by the team of designers and
programmers as a way to ensure that actual programming is likely to match design
specifications. Catching errors at the pseudocode stage is less costly than catching them later in
the development process. Once the pseudocode is accepted, it is rewritten using the vocabulary
and syntax of a programming language. Pseudocode is sometimes used in conjunction with
computer-aided software engineering-based methodologies.
It is possible to write programs that will convert a given pseudocode language into a
given programming language.
Example:
If student's marks are greater than or equal to 35
Print "passed"
else
Print "failed"

Q: What is flowchart?
A: A flowchart is a type of diagram that represents an algorithm, workflow or process,
showing the steps as boxes of various kinds, and their order by connecting them with arrows.
This diagrammatic representation illustrates a solution model to a given problem. Flowcharts
are used in analyzing, designing, documenting or managing a process or program in various
fields.
There are many different types of flowcharts, and each type has its own repertoire of
boxes and notational conventions. The two most common types of boxes in a flowchart are:
 a processing step, usually called activity, and denoted as a rectangular box
 a decision, usually denoted as a diamond.
Common shapes: The following are some of the commonly used shapes used in flowcharts.
Generally, flowcharts flow from top to bottom and left to right.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 79


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Shape Name Description


An arrow coming from one symbol and ending at another symbol
Flow Line represents that control passes to the symbol the arrow points to.
The line for the arrow can be solid or dashed.

Represented as circles, ovals or rounded (filled) rectangles. They


Terminal usually contain the word "Start" or "End", or another phrase
signaling the start or end of a process, such as "submit inquiry" or
"receive product".

Represented as rectangles. This shape is used to show that


Process something is performed. Examples: "Add 1 to X", "replace
identified part", "save changes", etc....

Represented as a diamond (rhombus) showing where a decision is


necessary, commonly a Yes/No question or True/False test. The
conditional symbol is peculiar in that it has two arrows coming
Decision out of it, usually from the bottom point and right point, one
corresponding to Yes or True, and one corresponding to No or
False. (The arrows should always be labeled.)

Represented as a parallelogram. Involves receiving data and


Input/Output displaying processed data. Can only move from input to output
and not vice versa. Examples: Get X from the user; display X.

Generally represented with a circle, showing where multiple


On-Page control flows converge in a single exit flow. It will have more
Connector than one arrow coming into it, but only one going out

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 80


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Q: What is a data structure? Explain types of data structures.


A: Data structures are a collection of data elements organized in a specified manner and
accessing functions are defined to store and retrieve data elements.
 Data structure measures efficiency of the algorithm.
 Every data structure combines its own advantages and disadvantages.
 Data structure operations include insertion, deletion, modification, searching sorting and
etc.
Generally data structures are classified into two. They are
i) Built-in data structures.
ii) User-defined data structures.
Built-in Data structures: These are the data structures which are already defined in the
language and they should be used in the same way as they are given.
Example: arrays, strings, structures and pointers.
User defined data structures: These are the data structures which are created by the
programmer according to the requirements of application.
Example: stacks, queues, linked lists, trees and etc.
User defined data structures are again classified into two:
I) Linear data structures.
II) Non-linear data structures
Linear-data structures: In this type of data structure, elements are organized sequentially. The
linear data structures are stacks, queues and linked lists.
Non-linear data structures: In this type of data structure, elements are not organized
sequentially. The non-linear data structures are trees and graphs.

Q: What are Arrays? What are the advantages and disadvantages of Arrays?
A: Array is set of values of similar type. Array elements share common name and array
elements are stored in sequential memory locations.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 81


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

To refer to the elements of array we use indexes. Array indexing starts from “zero”.
Predetermination of array size is must except in the case of giving values at time of declaring an
Array.
Advantages(Pros) of Arrays:
 It is capable of storing many elements at a time.
 It allows random accessing of elements using indexes.
Disadvantages(Cons) of Arrays:
 Predetermining the size of array is must.
 There is a chance of memory wastage.
 To delete one element in the array, we need to traverse (visit) throughout the array.
 To insert element into the array, we need to traverse throughout the array.

Q: What are the types of Arrays and how to create and initialize one dimensional Array?
A: Array is set of values of similar type. Array elements share common name and array
elements are stored in sequential memory locations.
Arrays can be of many types they are:
 One dimensional arrays(1-D)
 Two dimensional arrays(2-D) and
 Multi dimensional Arrays(N-D)
One dimensional Array: An array with only one subscript is called as single subscripted
variable (or) one dimensional Array.
Creation of Arrays: Creation of Array involves three steps. They are:
1) Declaring an Array (or) Declaration of Arrays
2) Creating memory locations
3) Putting values in to the memory locations
Declaration of Arrays: Arrays in java may be declared in two forms
Syntax: type arrayname[ ]; (or) type[ ] arrayname;

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 82


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Ex: int a[ ]; (or) int[ ] a;


Creating memory locations: After declaring an Array, we need to create it in the memory.
Java allows us to create arrays using “new” operator
Syntax: arrayname = new type[size];
Ex: a = new int[5];
It is also possible to combine above two steps (declaration & creation)
Syntax: type arrayname[ ]= new type[size];

Ex: int a[ ]=new int[5];


Initialization of Arrays: The final step is to put values into the array created. This process is
known as initialization. This is done using the array subscripts as shown below
Syntax: arrayname[subscript] = value; a memory
a[0] 10
Ex: a[0]=10; a[1] 20
a[1]=20;
a[2] 30
a[2]=30;
a[3] 40
a[3]=40;
a[4] 50
a[4]=50;
We can also initialize array automatically, in some way as the ordinary variables when
they are declared.
Syntax: type arrayname[ ] = { list of values };
Ex: int a[ ]={35, 40, 20, 57, 19};

To print the array we may write:


for (i=0;i<5;i++)
System.out.println(a[i]);

*** In Java, all arrays store the allocated size in a variable named “length”. We can obtain the
length of the array “a” using “a.length”.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 83


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Q: Explain 2-dimensional and multi dimensional arrays?


A: Two dimensional arrays: Double-dimensional arrays can represent the data in the form
of rows and columns i.e., by taking two indexes. Generally, these are used to work with
matrices. In Java, a Double-dimensional array can be declared as follows
Syntax: type arrayname[ ][ ] = new type[size][size];
(or)
type[ ][ ] arrayname=new type[size][size];

Example: int a[ ][ ]=new int[5][5]; (or) int[ ][ ] a=new int[5][5];


Array initialization done as follows:
int a[ ][ ]= {{10, 20, 30}, {40, 50, 60}, {70, 80, 90}};
here, a 0 1 2
a[0][0]=10 a[0][1]=20 a[0][2]=30 0 10 20 30

a[1][0]=40 a[1][1]=50 a[1][1]=60 1 40 50 60

a[2][0]=70 a[2][1]=80 a[2][2]=90 2 70 80 90


To print the array, we may write:
for(i=0; i<3; i++)
{
System.out.println(“ “);
for(j=0; j<3; j++)
{
System.out.print(“\t “ + a[i][j]);
}
}

Multi dimensional Arrays: Multi dimensional arrays usemore than two indexes to refer to its
elements. Generally, it represents a set of matrices.
For example, in Java a Three-dimensional Array can be declared as follows:
Syntax: type arrayname[ ][ ][ ]= new type[size][size][size];
(or)
type[ ][ ][ ] arrayname= new type[size][size][size];

Ex: int a[ ][ ][ ]= new int[2][2][3]; (or) int[ ][ ][ ] a=new int[2][2][3];

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 84


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Array initialization done as follows:


int a[ ][ ][ ]={{{10, 20, 30}, {40, 50, 60}}, {{70, 80, 90}, {15, 25, 35}}};
here, a[0][0][0]=10 0 1
a[0][1][1]=50 a 0 1 2 0 1 2
0 10 20 30 0 70 80 90
a[1][0][1]=80
1 40 50 60 1 15 25 35

To print the array, we may write:


for(i=0; i<2; i++)
{
System.out.println(“ “);
for(j=0; j<2; j++)
{
System.out.println(“ “);
for(k=0; k<3; k++)
System.out.print(“\t “ + a[i][j][k]);
}
}

Q: How do you calculate address of 1-D, 2-D and N-D arrays?


A:
Address Calculation in single (one) Dimension Array:

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 85


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Address of an element of an array say “A[ I ]” is calculated using the following formula:
Address of A [ I ] = B + W * ( I – LB )
Where,
B = Base address
W = Storage Size of one element stored in the array (in byte)
I = Subscript of element whose address is to be found
LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero)
Example: Given the base address of an array B[1300…..1900] as 1020 and size of each
element is 2 bytes in the memory. Find the address of B[1700].
Solution:
The given values are: B = 1020, LB = 1300, W = 2, I = 1700
Address of A [ I ] = B + W * ( I – LB ) = 1020 + 2 * (1700 – 1300)
= 1020 + 2 * 400
= 1020 + 800
= 1820 [Ans]

Address Calculation in Double (Two) Dimensional Array:


While storing the elements of a 2-D array in memory, these are allocated contiguous
memory locations. Therefore, a 2-D array must be linearized so as to enable their storage. There
are two alternatives to achieve linearization: Row-Major and Column-Major.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 86


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Address of an element of any array say “A[ I ][ J ]” is calculated in two forms as given:
(1) Row Major System
(2) Column Major System
Row Major System:
The address of a location in Row Major System is calculated using the following formula:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
Column Major System:
The address of a location in Column Major System is calculated using the following formula:
Address of A [ I ][ J ] Column Major Wise = B + W * [( I – Lr ) + M * ( J – Lc )]
Where,
B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
M = Number of row of the given matrix
N = Number of column of the given matrix

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 87


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Important: Usually number of rows and columns of a matrix are given ( like A[20][30] or
A[40][60] ) but if it is given as A[Lr- – – – – Ur, Lc- – – – – Uc]. In this case number of rows
and columns are calculated using the following methods:
Number of rows (M) will be calculated as = (Ur – Lr) + 1
Number of columns (N) will be calculated as = (Uc – Lc) + 1
Examples:
An array X [-15……….10, 15……………40] requires one byte of storage. If beginning
location is 1500. Determine the location of X [15][20].
Solution:
As you see here the number of rows and columns are not given in the question. So they are
calculated as:
Number of rows say M = (Ur – Lr) + 1 = [10 – (- 15)] +1 = 26
Number of columns say N = (Uc – Lc) + 1 = [40 – 15)] +1 = 26
(i) Column Major Wise Calculation of above equation
The given values are: B = 1500, W = 1 byte, I = 15, J = 20, Lr = -15, Lc = 15, M = 26
Address of A [ I ][ J ] = B + W * [ ( I – Lr ) + M * ( J – Lc ) ]
= 1500 + 1 * [(15 – (-15)) + 26 * (20 – 15)]
= 1500 + 1 * [30 + 26 * 5] = 1500 + 1 * [160]
= 1660 [Ans]
(ii) Row Major Wise Calculation of above equation
The given values are: B = 1500, W = 1 byte, I = 15, J = 20, Lr = -15, Lc = 15, N = 26
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
= 1500 + 1* [26 * (15 – (-15))) + (20 – 15)]
= 1500 + 1 * [26 * 30 + 5] = 1500 + 1 * [780 + 5]
= 1500 + 785
= 2285 [Ans]

Q: Explain the concept of ordered list.


Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 88
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

A: A List is an ordered Collection (sometimes called a sequence) of elements. Lists may


contain duplicate elements. In addition to the operations inherited from Collection, the List
interface includes operations for the following:
 Positional access  manipulates elements based on their numerical position in the list.
This includes methods such as get, set, add, addAll, and remove.
 Search  searches for a specified object in the list and returns its numerical position.
Search methods include indexOf and lastIndexOf.
 Iteration  extends Iterator semantics to take advantage of the list's sequential nature.
The listIterator methods provide this behavior.
 Range-view  The sublist method performs arbitrary range operations on the list.
The Java platform contains two general-purpose List implementations. ArrayList, which is
usually the better-performing implementation, and LinkedList which offers better performance
under certain circumstances.
Most polymorphic algorithms in the Collections class apply specifically to List. They are
 sort sorts a List using a merge sort algorithm, which provides a fast, stable sort.
 shufflerandomly permutes the elements in a List.
 reverse reverses the order of the elements in a List.
 rotate rotates all the elements in a List by a specified distance.
 swapswaps the elements at specified positions in a List.
 replaceAllreplaces all occurrences of one specified value with another.
 filloverwrites every element in a List with the specified value.
 copycopies the source List into the destination List.
 binarySearchsearches for an element in an ordered List using the binary search
algorithm.
 indexOfSubListreturns the index of the first sublist of one List that is equal to another.
 lastIndexOfSubListreturns the index of the last sublist of one List that is equal to
another.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 89


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Q: What is a stack?
A: Stack is a linear data structure in which elements are added and removed from only one
end. It is a structure, which works on the LIFO (Last In-First Out) principle.
In a stack, the elements are added at the top and removed from the top.
Graphical representation: Push Pop

Top

Operations on stack ADT: Stack operations include:


 push: pushing is to add elements on the top of the stack.
 pop: popping is removing elements from the top of the stack.
 isFull: isFull finds out whether the stack is full or not.
 isEmpty: it finds out whether the stack is empty or not.
 top: to return the top element of a stack.
 create: used to create an empty stack.
 display: used to display the data present in the stack.
The stack ADT is shown as given below:
Application of stacks:
i) Parenthesis matching.
ii) Keeping track of function calls.
iii) Recursive functions.
iv) Evaluating arithmetic expressions.
v) Conversion from infix to postfix expressions.

Q: How do you represent a stack using arrays?


A: For example, we take an array of 5 elements and a top pointer, which always points to the
top of the stack.
int stack [5];
int top = -1;
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 90
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

The top pointer should initially stored with’-1’, which indicates the “stack is empty”
Before inserting an element into the stack, a condition should be checked whether the
stack is full or not.
If stack is full then print the message “stack is full”. Otherwise, increment the top pointer
by one and insert the element into the stack.
Before deleting an element from the stack, a condition should be checked. Whether the
stack is empty or not.
If empty, then print a message “stack is empty”, otherwise delete the element to which
top pointer is currently pointing and decrement the top by 1.
Example: push(10) 4 push(20) 4 push(30) 4
3 3 3
30
2 2 2
1 20 1 20 1
top=0 10 0 top=1 10 0 top=2 10 0

push(40) 4 push(50) 50 4

40 3 40 3
2 30 2
30
1 1
20 20
top=3 0 top=4 0
10 10

Now, stack is pointing to the maximum position of array, since stack is full, and we
cannot insert items into the stack.
If we perform delete operation on the above stack, the top element 50 is deleted and top is
decremented by 1.
pop( ) 4 pop( ) 4
40 3 3
30 2 30 2
20 1 20 1
top=3 10 0 top=2 10
0

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 91


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Program to implement PUSH and POP operations on stack using array method.
class Stack
{
private static int MAX=5;
private int a[ ]=new int[MAX];
int top;
Stack( )
{
top= -1;
}
public void push(int v)
{
if(top>=MAX)
System.out.println("Stack is full");
else
{
top++;
a[top]=v;
}
}
public void pop( )
{
if(top= = -1)
System.out.println("Stack is empty");
else
{
System.out.println("Element deleted is:"+a[top]);
top- -;
}
}
public void display( )
{
if(top= = -1)
System.out.println("Stack is empty");
else
{
System.out.println("Stack elements:");
for(int i=top;i>=0;i- -)
System.out.println(a[i]);
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 92


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

} Save: StackArray.java
} Compilation: javac StackArray.java
class StackArray Execution: java StackArray
{ Output: Stack elements:
public static void main(String args[ ]) 50
{ 40
Stack s=new Stack( ); 30
s.push(10); 20
10
s.push(20); Element deleted is:50
s.push(30); Stack elements:
40
s.push(40); 30
s.push(50); 20
10
s.display( );
s.pop( );
s.display( );
}
}

Q: What is Arithmetic expression? What are its types?


A: An arithmetic expression is a combination of variables, constants and operators arranged
as per the syntax of the language.
Algebraic expression JAVA expression
ab-c a*b-c
(m+n)(x+y) (m+n)*(x+y)
3x2+2x+1 3*x*x+2*x+1
Types of expressions:
i) Infix expression: If the operator is in between operands, then the expression is said to be
infix.
Example: A+B, (A+B)+C.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 93


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

ii) Prefix expression: Operator preceded with two operands


Example: +AB
iii) Postfix expression: Operators follows the operands.
Example: AB+
Arithmetic expressions are evaluated according to BOEDMAS theory, i.e.:
B- Bracket.
O- Off.
E- Exponent.
D- Division.
M- Multiplication.
A- Addition.
S- Subtraction.

Q: Explain the process of converting “infix expression” to “postfix expression”.


A: Infix expression uses operator between the operands and it requires parenthesis for proper
evaluation.
Example: (a+b)*c+d*e
Postfix expression uses operator after the operands and it is does not include parenthesis.
Example: ab+c*de*+
Process:
 When an operand is encountered, it is directly printed.
 When a left parenthesis ‘(‘ is encountered, it is pushed onto the stack.
 When a right parenthesis ‘)’ is encountered, pop till all matching left parenthesis is
encountered. Print all the popped elements excluding parenthesis.
 When an operator is encountered, and the operator at the top of the stack has lower
priority, push it onto the stack.
 Otherwise, pop all the elements till an element with lower priority is found.
 Repeat the same process till the end of the equation.
 Finally, pop all the elements of stack and print them.
Example: consider the infix expression “(a+b)*c+d*e”.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 94
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Symbol Output Stack contents


Start Empty
( (
a a (
+ a (+
b ab (+

) ab+ Empty
* ab+ *
c ab+c *
+ ab+c* +
d ab+c*d +
* ab+c*d +*
e ab+c*de +*
End ab+c*de*+ Empty.

(Note: Refer practical program no: 8)

Q: Explain the process of evaluating postfix expression?


A: Postfix expression uses operator after the operands and it does not include parenthesis.
Example: Infix expression: (2+3)*4+5*2
Postfix expression: 2 3+4*5 2*+
Process: Postfix expression is scanned from left to right one at a time.
 If a number is encountered it is pushed onto the stack.
 If an operator is encountered, pop two operands from the stack and compute the result
onto the stack.
 Repeat the same process till the end of the expression.
 Finally pop the result from the stack and print it.
Example: consider the postfix expression “2 3+4*5 2*+”.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 95
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Symbol Computation Stack contents


Start Empty
2 2
3 2,3
+ 2+3 5
4 5,4
* 5*4 20
5 20,5
2 20,5,2
* 5*2 20,10
+ 20+10 30

(Note: Refer practical program no: 9)

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 96


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

UNIT-III
Q: What is recursion? And ow to use stack in Recursion? (OR) Execution of recursive
calls.
A: If a function is called within the same function, is said to be recursion. It means
recursion is the process by which a function calls itself; such function is called as recursive
function.
All recursive fumctions must have the following.
1. Base case (when to stop)
2. Work towards base case
3. Recursive call
Example:
factorial(5) = 5*4*3*2*1
again 4*3*2*1 is equal to (5-1) i.e 4!
From this we can write, factorial (5) =5*factorial(4)
=5*4*factorial(3)
=5*4*3*factorial(2)
=5*4*3*2*factorial(1)
=5*4*3*2*1
Code for the above example is:
public int factorial(int n)
{
if(n= =0 || n= =1)
return (1);
else
return(n*factorial(n-1)); //recursive call
}

Every call to the method creates a new set of local variables in the stack. So with the help
of stack only we can execute the recursive functions. Even sequence of function calls also gets
executed with the help of stacks.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 97
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

n=1
return to Funtion

n=2 n=2
return to Funtion return to Funtion

n=3 n=3
n=3
return to Funtion return to Funtion
return to Funtion
n=4 n=4
n=4 n=4
return to Funtion return to Funtion
return to Funtion return to Funtion

n=5 n=5 n=5 n=5 n=5

Initial After 1st recursion 2nd recursion 3rd recursion 4th recursion

n=1
return to Funtion
n=2 n=2*1=2
return to Funtion
return to Funtion
n=3 n=3 n=3*2=6
return to Funtion return to Funtion
return to Funtion
n=4 n=4 n=4
n=4*6=24
return to Funtion return to Funtion
return to Funtion return to Funtion
n=5 n=5 n=5 n=5 n=5*24=120
th
4 recursion Result

When the function execution completes the stack becomes empty.

Q: What are the types of recursion? (OR) Variants of Recursion.


A: If a function is called within the same function, is said to be recursion. It means
recursion is the process by which a function calls itself; such function is called as recursive
function.
Recursion is again of 1) linear recursion and
2) non- linear recursion (binary recursion)

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 98


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Linear recursion: If a function is called itself only once then such functions are said to be
linear recursive functions.
void main( )
{
A( );
}
void A( )
{
:
A( );
:
}
Non-Linear recursion: If a function is called itself more than one time such functions are said
to be non-linear recursive functions.
void main( )
{
A( );
}

void A( )
{
A( );
:
A( );
:
}

Q: Explain the difference between iteration and recursion?


A: Iteration:
 Repeated execution of statements is known as Iteration.
 An iterative loop is executed as long as the condition is true.
 Iterative logic is executed fast when compared to recursion.
 Iterative approach involves 4 steps; initialization, condition, execution and updation
but recursion contains only base condition(termination condition).

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 99


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

public int factorial(int n)


{
int fact=1;
if(n= =0 || n= =1)
return (1);
else
{
for(int i=2; i<=n; i++)
fact= fact*i;
return fact;
}
}
Recursion:
 If a function is called within the same function, it is said to be recursion.
 In this, a function is called within the same function till it meets a proper condition.
 Recursion keeps your code short and simple.
 Recursive logic gets executed slowly when compared to iteration due to overhead of
maintaining stack.
public int factorial(int n)
{
if(n= =0 || n= =1)
return (1);
else
return(n*factorial(n-1)); / /recursive call
}

Q: What is Queue? What are the operations of Queue?


A: A Queue is a linear data structure, in which elements are added at one end (known as
rear) and elements are removed from the other end (known as front end). Queue is also be
referred as ”First In-First Out(FIFO)” data structure.
 A Queue has front and rear.
 Representation: Deletion insertion

Front rear
end end
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 100
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Operation on Queue ADT:


In a queue, insertion occurs at the rear end and deletion occurs at the front end of the list.
This is called as FIFO method.
 qstore(Enqueue): adding elements at the end of the queue.
 qdelete(Dequeue): removing elements from the front of the queue.
 isFull: used to find out whether the queue is full or not.
 isEmpty: used to find out whether the queue is empty or not.
 create: used to create an empty queue.
 first(front): refers to the first element of the queue.
 last(rear): refers to the last element of the queue.
Applications of queue: Queue is used in many applications such as,
1) Printing documents using computer: When documents are to be printed, the printer
prints the documents in FIFO method only.
2) Reservation oriented information systems: Reservations such as air ticket or railway
reservation systems, use queue to issue reservations on FIFO basis.
3) Computer networks: Computer network use queues to give access from server to server
clients, who are connected to the server in FIFO method.
4) Railroad rearrangement, wire routing, machine shop simulation

Q: How do you represent Queues using arrays?


A: Implementation of queue using arrays:
For example, we take an array of 5 elements and front and rear variables.
 The initial values of front and rear variable should be “-1”.
 The rear pointer should increment when an element is added into the queue.
 Whereas, front pointer should increment when an element is deleted.
 When the first element is added into the queue, assign front with ‘0’.
 Queue emptiness can be checked with the following conditions.
if(front= =-1) Queue is empty.
if(front= =rear+1) Queue is now empty.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 101


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

 Queue fullness can be checked with following conditions.


if(rear= =size-1) Queue is full.
Example:
int Queue[5];
int rear= -1,front= -1;

0 1 2 3 4
i) Add 10 to this queue.
10

0 1 2 3 4
front=0
rear=0

ii) Add 20 to the queue.


10 20

0 1 2 3 4
front rear

iii) Add 30 to the queue.


10 20 30

0 1 2 3 4
front rear
iv) Now delete an element:
20 30

0 1 2 3 4
front rear
Program to implement Queue using array method.
class Queue
{
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 102
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

private static int MAX=5;


private int a[ ]=new int[MAX];
int front, rear;
Queue( )
{
front= rear = -1;
}
public void insert(int v)
{
if(rear<MAX)
{
rear++;
a[rear]=v;
}
else
System.out.println("Queue is full");
}
public void del( )
{
if(rear= = -1)
System.out.println("Queue is empty");
else
{
front++;
System.out.println("Element deleted is:"+a[front]);
}
}
public void display( )
{
if(rear= = -1)
System.out.println("Queue is empty");
else
{
System.out.println("Queue elements:");
for(int i=front+1; i<=rear; i++)
System.out.println(a[i]);
}
}
}
class QArray
{

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 103


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

public static void main(String args[ ])


{
Queue q=new Queue( );
q.insert(10);
q.insert(20);
q.insert(30);
q.insert(40);
q.insert(50);
q.display( );
q.del( );
q.display( );
}
}
Save: QArray.java
Compilation: javac QArray.java
Execution: java QArray
Output: Queue elements:
10
20
30
40
50
Element deleted is: 10
Queue elements:
20
30
40
50
Q: What are circular Queues and Double Ended queues?
A: Circular Queue: A circular Queue is a Queue in which all nodes are treated as circular
such that the first node follows the last.
Using arrays Using Linked list
front rear
A[0] A[n-1]

..
. front rear

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 104


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Operations on circular queue:


i) qstore ii) qdelete iii) isFull iv) isEmpty v) create
Applications of circular queue:
1) Adding large numbers: large integers can be added easily using circular queues. Here, the
rightmost digit is placed in the front node and leftmost digit is placed in the rear node.
2) Memory management: The unused memory locations in the case of ordinary queue can
be utilized in circular queues.
3) Computer controlled traffic system: In computer controlled traffic system, circular
queues are used to switch on the traffic lights one by one repeatedly as per the time set.
(Note: Refer practical program no: 14)

Dequeue (Double Ended Queue): In this insertion and deletion occur at both the ends i.e. front
and rear end of the queue.

Insertion deletion

Deletion front rear insertion


Operations on dequeue:
1) insertFirst( ) : to add element at the end of a dequeue.
2) insertLast( ) : to add element at the begging of a dequeue.
3) deleteFirst( ): to remove first element of the dequeue.
4) deleteLast( ): to remove last element of the dequeue
5) isFull( ): to find out whether the dequeue is full
6) isEmpty( ): to find out whether the dequeue is empty.
7) create( ): to create an empty dequeue.
Q: What are linked lists? What are its advantages? And explain types of linked lists?
A: Linked list is a type of data structure that holds set of nodes linked to each other. Every
node consists of data ( information) part and link (reference) part .

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 105


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Data Link

Data part: It stores the information of node


Link part: It stores the address of next node. It is also called as ‘next pointer’
Advantages:
 In linked lists there will not be any memory wastage (or) storage.
 To insert an element in the linked list we need not traverse throughout the list.
 To delete an element in the linked list we need not traverse throughout the list.
 Predetermining of number of data elements is not necessary.
Types of linked lists: Linked lists are mainly of 4 types
i) Single linear linked list
ii) Single circular linked list
iii) Double linear linked list
iv) Double circular linked list
Single linear linked list: In this, every node consists of two parts information and reference
parts it allows one-way and linear traversal in the list. End of the list is points to NULL
node1 node2 node2 node4
NULL

info n2 info n3 info n4 info


Single circular linked list: In this every node consists of two parts information and reference
part. It allows one-way and circular traversal in the list. There is no end-node in a list, because
the last node is linked to the first node
1000 1010 1020 1030
10 1010 20 1020 30 1030 40 1000

node1 node2 node3 node4

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 106


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Double linear linked list: In this every node, consist of three parts; information and two
reference parts. Left link stores the address of previous node and right link store the address of
next node. It allows two-way and linear traversal in the list.
node1 node2 node3
null Data Right Left Data Right Left Data null
Link Link Link Link

Double circular linked list: In this every node consists of three parts; information and two
reference parts. It allows two-way and circular traversal in the list.
node1 node2 node3
Left Data Right Left Data Right Left Data Right
Link Link Link Link Link Link

Q: What are the operations on linked list ADT?


A: Linked list allows many operations on it.
 Creating a list: It involves allocating memory and reading data for nodes.
 Traversing a list: Visiting all the nodes in a specific order.
 Inserting an element in the list: Inserting a new node in the linked list at a given position.
 Deleting an element from the list: Delete a node at given position or given value.
 Destroying the list: De allocates memory for all the nodes of a linked list.
 Printing the list: Displaying all the elements of the list.
 Searching for an element in the list.
 Modifying an element in the list.
 Sorting the list into specific order.
Q: What are the applications of linked list?
A: Following are the applications of linked list:
 Polynomial addition and multiplication: Polynomial equations can be added and multiply
easily using linked lists. Linked lists hold each coefficient and exponential part as
information parts.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 107
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

 Radix sort: Radix sort uses linked list to perform sorting.


 Symbol table implementation: symbol tables are used in compiler construction and
related fields.
 Used to perform arithmetic operations on large numbers.
 Used to implement stacks and queues.
 Memory management.
Q: Explain creation, insertion and deletion of nodes in a single linked list.
A: Linked list is a type of a data structure that holds nodes linked to each other. In a single
linked list, every node consists of two parts information & reference parts.
Creating node: This operation is performed by a function called create( ).
 Create an ADT named “node” that contains “reference” and “information” parts.
 Allocate memory for “first” node. Treat the same as “list” and makes the reference part
null.
We create the list with the first data 10
1010 node address
10 NULL

Node1
Now, we add one more node to the list with the data 20 and later 30, 40 then the list will
be: 1010 1020 1030 1040
10 1020 20 1030 30 1040 40 NULL

node1 node2 node3 node4


Inserting node: this operation allows inserting the node in the linked list at the position we
require. This operation can be performed by the function insert( ).
 Take a reference named “ptr” and move it from first node to a node that is prior to the
inserting position.
 Allocate memory for a temporary node, read information
 Establish links as shown below.
 Handle it differently if the insertion is at last node.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 108


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

1010 1020 1030 1040


10 1020 20 1050 30 1040 40 NULL

node1 node2 node3 node4


1050
25 1030
New node
Deleting a node: Take a reference part named “ptr” and move it from first node to a node that
is prior to the deleting position. Disconnect the link between the nodes and establish new link
between the nodes that are present before and after the deleted node.

Example: 1010 1020 1030 1040


10 1020 20 1030 30 1040 40 NULL

node1 node2 node3 node4


Now, we delete a node whose data is 20 from the above list:
1010 1030 1040
10 1020 30 1040 40 NULL

node1 node3 node4


(Note: Refer practical program no: 12)
Q: Explain the process of creation, insertion and deletion in double linked list.
A: Linked list is a type of data structure that holds nodes linked to each other. In a double
linked list, every node consists of three parts; Information (Data) and two reference parts. First
reference node (Left Link) holds the address of previous node and other (Right) holds the
address of next node. It allows two-way and linear traversal in the list.
Creating a node:
 Create an ADT named “node” that contains two references and information parts.
 Allocate memory for “first” node, treat the same as “list” and make its reference parts as
null.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 109


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

We create the list with the first data 10.


1010
NULL 10 NULL

Node1
Now, we can add one more data 20 and later 30, 40, and then the list will be:
1010 1020 1030 1040
NULL 10 1020 1010 20 1030 1020 30 1040 1030 40 NULL
L 0
node1 node2 node3 node4
Inserting a node:
 Take a reference part named “ptr” and move it from first node to a node that is prior to
the inserting position.
 Allocate memory for a temporary node, read information.
 Make links as shown in the diagram.
 Handle it differently if it is insertion at last node.
1010 1020 1030 1040
NULL 10 1020 1010 20 1050 1050 30 1040 1030 40 NULL

node1 node2 node3 node4


1050

1020 25 1030

Deleting a node: Take a reference part named “ptr” and move it from first node to a node that
is prior to the deleting position. Disconnect the link between the nodes and establish new link
between the nodes that are present before and after the deleted node.

1010 1020 1030 1040


NULL 10 1020 101 20 1030 1020 30 1040 1030 40 NULL
0
node1 node2 (X)deleted node node4
(Note: Refer practical program no: 13)

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 110


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Q: How do you represent Linked List?


A: Let LIST is linear linked list. It needs two linear arrays for memory representation. Let
these linear arrays are INFO and LINK. INFO[K] contains the information part and LINK[K]
contains the next pointer field of node K.
A variable START is used to store the location of the beginning of the LIST and NULL
is used as next pointer sentinel which indicates the end of LIST. It is shown below.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 111


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Q: How do you represent Stacks and Queues using Linked List?


A: Stacks using linked list: Stacks can also be implemented by using linked lists. The linked
stack requires two pointers:
i) Head pointer: stores the address of first node of the linked stack and
ii) Top pointer: stores the address of last node.
Initially the head and top pointers should be stored with NULL. If top is NULL which
means the linked stack is empty.
Example: Let us draw a linked stack and insert or push some nodes into the linked stack.
push(10): 1010
10 NULL

Head=1010
Top=1010
push(20): 1010 1020
10 1020 20 NULL
Head=1010
Top=1020
push(30) 1010 1020 1030
10 1020 20 1030 30 NULL

Head=1010
Top=1030
Now, we perform pop( ) operation on the above linked stack:30 is deleted.
pop( ): 1010 1020
10 1020 20 NULL

Head=1010
Top=1020
pop( ): 1010
10 NULL

Head=1010
Top=1010
If we perform again pop( ) operation on the above Stack, the linked stack is empty, i.e.
Head=NULL, Top=NULL.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 112
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Queues using linked list: Queue can also be implemented using linked list and known as
“linked Queue”. Linked Queue requires two pointers. Initially these pointers are stored with
NULL.
 Front pointer always stores the address of first node and
 Rear pointer stores the address of last node.
Example: Let us draw a linked queue and insert some nodes into the linked queue.
insert(10): 1010
10 NULL

front=1010
rear=1010
insert(20): 1010 1020
10 1020 20 NULL
front=1010
rear=1020
insert(30) 1010 1020 1030
10 1020 20 1030 30 NULL

front=1010
rear=1030
Now, we perform qdelete( ) operation on the above linked queue:10 is deleted.
qdelete( ): 1020 1030
20 1030 30 NULL

front=1020
rear=1030
qdelete( ): 1030
30 NULL

front=1030
rear=1030
If we perform again deletion operation on the above Queue, the linked queue is empty,
i.e. front=NULL, rear=NULL.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 113
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

UNIT-IV
Q: What is a tree? Explain tree terminology?
A: A tree is a finite set of nodes and it has a unique node called the “root” node.
root
A Level1

B C Level2

D E F G Level3

H I J K Level4

Node: Individual element of a tree is called as a node. In the above tree A, B, C, D, E, F, G, H,


I, J, &K are nodes.
Root: The node at the top of a tree is called the root (or) it is an actual node from where tree
begins. There is only one root in a tree.
Parent node: Any node (except root) that has at least one child node, is called parent.
Child node: All the nodes except root are child nodes.
Leaf: A node that has no child node can be called as leaf node.
Path: The sequence of lines which connect node to node of tree called path.
Sub tree: A sub tree constitutes of a node and all its descendants.
Visiting: Reaching a particular node to either print or perform some operation on it.
Traversing: Traversing means to visit all the nodes in some specific order.
Level: The level refers to the numbers of generations from the root of a tree (it is also called as
depth).
Degree: The number of sub trees for a node is called as degree.
Degree of (A) =2
Degree of (B) =2
Degree of (D) =3

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 114


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Q: What is binary tree? What are the advantages of binary tree?


A: A binary tree is a non-linear data structure in which each node has maximum of two child
nodes. The tree connections are called as branches.
 Binary tree is the one in which each node has maximum of two-child nodes.
 In a binary tree, the degree of every node is less than or equal to two (<=2).
 Binary tree does not allow duplicate values.
 While constructing a binary tree, if an element is less than the value of its parent node, it
is placed on left side of it, otherwise right side.
 A binary tree is shown for the elements 40, 56, 35, 48, 22, 65, 28.

40

35 56

22 48 65

28
Advantages:
 Searching in binary tree becomes faster.
 Binary tree provides 6 traversals.
 Two of six traversals give sorted order of the elements.
 Maximum and minimum elements can be directly picked up.

Q: What are the operations of binary tree ADT?


A: The operations of binary tree:
1) isEmpty( ): returns true if empty, returns false otherwise.
2) root( ): returns the root element.
3) makeTree(root, left, right): creates a binary tree with root as the root element,
left(right) as the left(right) subtree.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 115


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

4) preorder( ): preorder traversal of binary tree.


5) inorder( ): In order traversal of binary tree.
6) postorder( ): post order traversal of binary tree.
7) removeLeftsubtree( ): removes the left subtree and return it.
8) removeRightsubtree( ): removes the right subtree and return it.

Q: Explain the implementation of a binary tree.


A: The implementation of binary tree includes following operations:
 Creating a tree.
 Inserting a node.
 Traversing.
 Deleting a node.
 Modifying a node.
 Searching a node.
Creation:
 To create a binary tree, first create an empty node whose left and right are set to null.
 For the first time, create a node and read a value and take it as root.
 Next onwards, check whether the element is less than or greater than the root.
 If the element is less than root element continue with left sub tree.
 If the element is greater than root element continue with right sub tree.
 Repeat the above two steps till an empty node encounters.
Example: Let us create a binary tree from the following input:
10, 8, 15, 20, 5, 12, 9, 18, 1, 30

10

8 15

5 12 20
9

1 18 30

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 116


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Insertion:
 First, check whether the element is less than or greater than the root element.
 If the element is less than root, continue with left sub tree.
 If the element is greater than root, continue with right sub tree.
 Repeat the above two steps till an empty node encounters.
 Create a node and insert it there.
Traversing: Traversing is a method of visiting every node in a specific order. The main three
traversals of a binary tree are:
i) In order.
ii) Pre order.
iii) Post order.
In order traversal: It gives us element in ascending order. In order traversal follows LVR
method (L-left, V-Visit vertex, R-Right).
1) Move to the root node of a tree.
2) Move to its left node if exists.
3) Repeat the second step till a node with no left encounters.
4) Now, print the element and move to right if it exists.
5) Repeat the above three steps for all pending nodes in a stack manner.
LVR(tree t)
{
if(t)
{
LVR(t.left);
System.out.println(t.x);
LVR(t.right);
}
}
Pre order traversal: It follows VLR method.
1) Move to the root node of a tree.
2) Print the element and move to left node if exists.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 117


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

3) Repeat the second step till a node with no left encounters.


4) Now, move to right if it exists and print element.
5) Repeat the above three steps for all pending nodes in a stack manner.
VLR(tree t)
{
if(t)
{
System.out.println(t.x);
VLR(t.left);
VLR(t.right);
}
}
Post order traversal: It follows LRV method.
1) Move to the root node of a tree.
2) Move to the left node if exists.
3) Repeat the second step till a node with no left encounters.
4) Now, move to right if it exists.
5) Repeat from step2 till a node with no left and no right encounters
6) Print the element.
7) Repeat the above three steps for all pending nodes in a stack manner
LVR(tree t)
{
if(t)
{
LVR(t.left);
LVR(t.right);
System.out.println(t.x);
}
}
For the above created tree, the result for:
In order traversal: 1 5 8 9 10 12 15 18 20 30
Pre order traversal: 10 8 5 1 9 15 12 20 18 30
Post order traversal: 1 5 9 8 12 18 30 20 15 10

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 118


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Deletion: To delete a node in the tree, first search the node.


 If the deleting node has no children, delete it directly.
 If the deleting node has one child, the parent node must be linked to the child node, and
delete the node.
 If the deleting node has two children, find minimum value in its right sub tree. Replace
the element to be deleted with minimum element and repeat the same process to delete
the node containing minimum element.
Modifying a node: To modify a node, search for the node in the tree and then modify the node
reading new values using modify ( ) method.
Searching a node: To search a node in the tree, start from the root node till you find the node
that you search.
//Program to construct Binary Search Tree and implement Tree Traversing Techniques.
class tree
{
int x;
tree left;
tree right;
}
class BTree
{
private tree t;
BTree( )
{
t=null;
}
public void insert(int v)
{
t=insert(t, v);
}
public void showLVR( )
{
System.out.println("\nLVR :\n");
LVR(t);
}
public void showVLR( )
{
System.out.println("\nVLR :\n");
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 119
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

VLR(t);
}
public void showLRV( )
{
System.out.println("\nLRV :\n");
LRV(t);
}
tree insert(tree t, int v)
{
if(t= =null)
{
t = new tree( );
t.x = v;
t.left = null;
t.right = null;
}
else if(v<t.x)
t.left = insert(t.left, v);
else if(v>t.x)
t.right = insert(t.right, v);
return t;
}
public void LVR(tree t)
{
if(t!= null)
{
LVR(t.left);
System.out.print("\t"+t.x);;
LVR(t.right);
}
}
public void LRV(tree t)
{
if(t!= null)
{
LRV(t.left);
LRV(t.right);
System.out.print("\t"+t.x);
}
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 120


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

public void VLR(tree t)


{
if(t!= null)
{
System.out.print("\t"+t.x);
VLR(t.left);
VLR(t.right);
}
}
}
class BTreeTest
{
public static void main(String args[ ])
{
BTree t1=new BTree( );
t1.insert(30);
t1.insert(20);
t1.insert(10);
t1.insert(40);
t1.showLVR( );
t1.showVLR( );
t1.showLRV( );
}
}
Save: BTreeTest.java
Compilation: javac BTreeTest.java
Execution: java BTreeTest
Output: LVR : 10 20 30 40
VLR : 30 20 10 40
LRV : 10 20 40 30
Q: What is Traversing? Explain “in order”, “post order” and “pre order” traversals in
binary trees.
A: Refer previous question.
Q: What is a graph? Explain types of graphs?
A: A graph is defined as a set of nodes or vertices and a set of lines or edges that connect the
two vertices. The Graph ‘G’ consists of two sets: Vertex set called ‘V’ and edge set called ‘E’.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 121
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

.’. G= (V, E)
 Vertices are also called as nodes or points, displayed as circles.
 Edges are called as lines or arcs.
 An edges with orientation ( ) is directed edge, while an edge with no orientation ( -- ) is
undirected edge.
Types of graphs:
1. Directed graph: If every edge in the graph is directed edge, then that graph is called as
directed graph. A B
V= {A, B, C, D, E } C D
E={ (A, B), (A, C), (A, E), (B, D), (C, E), (D, E)} E
2. Undirected graph: Undirected graph is a graph, in which every edge has no direction.
V= {v1, v1, v3, v4} v1 v2
E={(v1,v2),(v1,v3),(v2,v1),(v2,v4),(v3,v1),(v3,v4),v4,v2),(v4,v3)} v3 v4
3. Connected graph: A graph ‘G’ is connected if there is a path between every pair of
vertices.
4. Sub graph: Sub graph is a graph in which vertex& edge sets are sub sets of G.
5. Trivial graph: It is a graph with only one vertex without any edge.
6. Complete graph: A graph G is said to be complete graph with ‘n’ vertices has n(n-1)/2
edges.

7. Weighted graph: A graph ‘G’ is weighted, if each edge in G is assigned a non negative
numerical value. 15 20

8. Connected directed graph (or) strongly connected graph: A directed graph ‘G’ is said
to be strongly connected, if for each pair of vertices (v1, v2) there is a path from v1 to v2
and v2 to v1.
A B

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 122


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

9. Loop: A node is connected to itself be called loop. A B

10.Insolated node: A node which is not adjacent to any other node is called isolated node.
11.Null graph: A graph containing only isolated nodes is called a Null graph.
A B

C D

Applications of graphs: Graphs are used in many applications. They are used in
i) Analysis of electrical networks.
ii) Study of molecular structure.
iii) The representation of airlines routes.
iv) Networks.
v) Topological sorting.
vi) Finding shortest paths.
Q: What are the operations of Graph ADT?
A: The Graph ADT refers to all vertices of graphs, whether directed, undeirected,
weightedor unweighted.
4. vertices( ): returns the number of vertices in the graph.
5. edges( ): returns the number of edges in the graph.
6. existsEdge(i, j) ): returns true if edge(i, j) exists, false otherwise.
7. putEdge( ): puts the edge into the graph.
8. removeEdge(i, j): removes the edge (i, j).
9. degree(i): returns the degree of the vertex i, defined only for undirected graphs.
10.inDegree(i): returns the in-degree of vertex i.
11.outDegree(i): returns the out-degree of vertex i.

Q: How do you represent a graph?


A: A graph can be represented in two methods
i) Linear representation (or) Adjacency matrix representation.
ii) Linked representation (or) adjacency list.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 123
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Adjacency matrix: In this representation the size of square matrix is taken as equal to the
number of vertices in the given graph. The elements of adjacency matrix are filled with either 1
or 0. If an edge is presented between (Vi, Vj) then the element is filled with 1. Otherwise the
element value is set with’0’.
G Graph
V Set of Vertices
(i, j) Edge connecting Vi and Vj
A[i][j] Adjacency matrix element
i, j Vertices

If ‘G’ is a digraph:
1 if (i, j) exists
A[i][j] = 0 otherwise
If ‘G’ is a undirected graph:
1 if (i, j) or (j, i) exists
A[i][j] = 0 otherwise.
Example: 1 2 3 4
1) 1 V={ 1, 2, 3, 4} 1 0 1 0 1
2
E= {(1, 2), (1,4), (2,4), (3,1), 2 0 0 0 1
(3,2), (4,3)} 3 1 1 0 0
3 4 4 0 0 1 0

Directed graph

v1 v2 v3 v4 v5
V1 V2 V={ v1, v2, v3, v4}
2)
E= {(v1, v2), (v1, v3), (v2, v1), v1 0 1 1 0 0
v2 1 0 1 0 0
V3 (v2, v3), (v3, v1), (v3, v2)
(v3, v4), (v3, v5), (v4, v3) v3 1 1 0 1 1
V5 v4 0 0 1 0 1
V4 (v4, v5), (v5, v3), (v5, v4)}
v5 0 0 1 0 1
Undirected graph
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 124
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Adjacency Lists: Graphs can be represented as adjacency lists that use arrays of linked lists.
Example: vertices
1 2 3 4 null
1 V={ 1, 2, 3, 4}
E= {(1,2), (1,3), (1,4),
2 1 3
null
(2,1), (2,3), (3,1) 3 null
2 3 1 2 4
(3,2), (3,4), (4,1)
(4,3) } 4 1 3 null
4

Undirected graph

vertices
1 V={ 1, 2, 3, 4} 2 3
1 null
E= {(1,2), (1,3), (2,4),
(3,2), (4,3) } 2 4 null
2 3
3 2 null
4
4 3 null

Directed graph

Q: Explain Graph traversals (or) Explain depth first and breadth first search methods.
A: There are any mainly two methods for traversing in a graph.
i) DFS(Depth First Search)
ii) BFS(Breadth first search)

DFS: It uses STACK to hold the nodes that are waiting to be processed
 First we examine the starting node ‘A’.
 Then we examine each node along a path ‘P’, which begins at ‘A’ .i.e. we process one of
the neighbors of ‘A’ and continue along the path.
 After coming to the end of ‘P’. we back track on ‘P’ until we can continue along another
path.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 125
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

1 6 7
A D G

2 9 8 Result: ABCFIDGHE
B E H

3 4 5
C F I

Algorithm:
1. Initialize all nodes to ready state.
2. Start with a node and push the node ‘A’ in the stack.
3. POP the top node ‘X’ from the stack. Print X.
4. Push all its neighbors omitting the processed ones in to the Stack.
5. Repeat the above two steps till all the elements of graph are visited.
6. Pop all the elements of the stack and print them to complete DFS.
Pseudo code to implement DFS (Depth First Search)
void DepthFirst(Graph G)
{
boolean visited[MAX];
int v;
for(all v in G)
visited[v]=FALSE;
for(all v in G)
if(!visited[v])
traverse(v);
}
void traverse(int v)
{
int w;
visited[v]=TRUE;
visit(v);
for( all w adjacent to v)
if(!visited[w])
traverse(w);
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 126
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

BFS: It uses QUEUE to hold node that are waiting to be processed.


 First we examine the starting node ‘A’.
 Then we examine all the neighbors of ‘A’.
 We continue with the other nodes in the same manner. No node is processed more than
once. 1 4 6
A D G

2 3 7 Result: ABEDCGHFI
B E H

5 8 9
C F I

Algorithm:
1. Initialize all nodes to ready state.
2. Start with a node and place it in the Queue.
3. remove an element ‘X’ from queue and Print X.
4. Place all its neighbors omitting the processed ones in the Queue
5. Repeat the above two steps till all the elements of graph are visited.
6. Delete all the elements of the queue and print them to complete BFS.
Pseudo code to implement BFS (Breadth First Search):
void BreadthFirst(Graph G)
{
Queue q;
boolean visited[MAX];
int v,w;
for(all v in G)
visited[v]=FALSE;
initialize(q);
for(all v in G)
{
if(!visited[v])
{
addQueue(v,q);
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 127
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

do
{
deleteQueue(v,q);
visited[v]=TRUE;
visit(v);
for( all w adjacent to v)
if(!visited[w])
addQueue(w);
}while(!empty(q));
}
}
}

Q: Explain spanning trees?


A: A spanning tree is a sub graph of G (where G is undirected graph) is a tree and contains
all the vertices of G. A minimum spanning tree is a spanning tree, but has weight associated
with the edges, and the total weight of the tree is at a minimum.
A minimum spanning tree should satisfy the following conditions.
 It should be a sub graph of the main graph.
 It should have all the vertices of ’G’.
 The number of edges should be n-1 and there should not be any cycle.
 The total weight of the tree should be least.
For, example considers the following graphs.
A Graph ‘G” Three (of the many possible) spanning trees from graph G.

A weighted graph G. The minimum spanning from weighted graph G

2 2
3 4 5 3
6
1 1
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 128
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

There are two different algorithms to find out minimum spanning tree:
 Kruskal’s algorithm
 Prim’s algorithm

Q: Explain about Prim’s algorithm.


A: One-way to compute a minimum spanning tree is to grow in successive stages. In each
stage, one node is picked as the root, and we add an edge, and thus an associated vertex, to the
tree. In this algorithm, at each stage, a new vertex to add to the tree by choosing the edge (u, v)
such that the cost of (u, v) is the smallest among all edges where u is in the tree and v is not.
Initially, v1 is in the tree as a root with no edges. Each step adds one edge and vertex to the tree.
Ex: 2 V2
V1
Vertex Visited Dist Path
4 1 3 8 V1 T 0 -
V2 F X -
V3
6 V4 2 V5
V3 F X -
V4 F X -
8 2 3 5 V5 F X -
V6 F X -
V6
1 V7
V7 F X -

Step- 1: step- 2:
Select v1 and update the Select v4 the vertex whose
adjacent vertex weights. weight is minimum and
update the adjacent vertex
weights.
Vertex Visited Dist Path Vertex Visited Dist Path
V1 T 0 V1 V1 T 0 V1
V2 F 2 V1 V2 F 2 V1
V3 F 4 V1 V3 F 4 V1
V4 F 1 V1 V4 T 1 V1
V5 F X - V5 F 2 V4
V6 F X - V6 F 2 V4
V7 F X - V7 F 3 V4

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 129


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Step- 3: Step- 4:
Select v2 the vertex whose weight Select v5 the vertex whose weight
is minimum and update the is minimum and update the
adjacent vertex weights. adjacent vertex weights.
Vertex Visited Dist Path Vertex Visited Dist Path
V1 T 0 V1 V1 T 0 V1
V2 T 2 V1 V2 T 2 V1
V3 F 4 V1 V3 F 4 V1
V4 T 1 V1 V4 T 1 V1
V5 F 2 V4 V5 T 2 V4
V6 F 2 V4 V6 F 2 V4
V7 F 3 V4 V7 F 3 V4

Step- 5: Step- 6:
Select v6 the vertex whose weight Select v7 the vertex whose weight
is minimum and update the is minimum and update the
adjacent vertex weights. adjacent vertex weights.
Vertex Visited Dist Path Vertex Visited Dist Path
V1 T 0 V1 V1 T 0 V1
V2 T 2 V1 V2 T 2 V1
V3 F 4 V1 V3 F 4 V1
V4 T 1 V1 V4 T 1 V1
V5 T 2 V4 V5 T 2 V4
V6 T 2 V4 V6 T 2 V4
V7 F 1 V6 V7 T 1 V6

Step- 7: The accepted from the graph to form


Select v3 the vertex whose the optional spanning tree are (v2, v1) (v3,
weight is minimum and v1) (v4, v1) (v5, v4) (v6, v4) (v7, v6)
update the adjacent vertex 2
V1 V2
weights.
Vertex Visited Dist Path 4 1
V1 T 0 V1
V2 T 2 V1 V3 V4
2 V5

V3 T 4 V1
V4 T 1 V1 2
V5 T 2 V4
1
V6 T 2 V4 V6 V7

V7 T 1 V6
Total cost= 2+4+1+2+2+1=12

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 130


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Q: Explain about Kruskal’s algorithm.


A: This algorithm is used to find the minimum spanning forest in a possibly disconnected
graph. Below are the steps for finding MST using Kruskal’s algorithm
1. Sort all the edges in non-decreasing order of their weight.
2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If
cycle is not formed, include this edge. Else, discard it.
3. Repeat step#2 until there are (V-1) edges in the spanning tree.
Let us understand it with an example: Consider the below input graph.

The graph contains 9 vertices and 14 edges. So, the minimum spanning tree formed will
be having (9 – 1) = 8 edges.
After sorting:
Weight Src Dest
1 7 6
2 8 2
2 6 5
4 0 1
4 2 5
6 8 6
7 2 3
7 7 8
8 0 7
8 1 2
9 3 4
10 5 4
11 1 7
14 3 5
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 131
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Now pick all edges one by one from sorted list of edges

1. Pick edge 7-6: No cycle is formed, include it.

2. Pick edge 8-2: No cycle is formed, include it.

3. Pick edge 6-5: No cycle is formed, include it.

4. Pick edge 0-1: No cycle is formed, include it.

5. Pick edge 2-5: No cycle is formed, include it.

6. Pick edge 8-6: Since including this edge results in cycle, discard it.

7. Pick edge 2-3: No cycle is formed, include it.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 132


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

8. Pick edge 7-8: Since including this edge results in cycle, discard it.

9. Pick edge 0-7: No cycle is formed, include it.

10. Pick edge 1-2: Since including this edge results in cycle, discard it.

11. Pick edge 3-4: No cycle is formed, include it.

Since the number of edges included equals (V – 1), the algorithm stops here.

Q: What is searching? Explain Linear and Binary search techniques.


A: Searching is a process of finding a value in a list of values. To search a value in a list of
values there are different searching techniques, among them few are:
1. Sequential (or) linear search
2. Binary (or) logarithmic search
Linear search:
 This searching is also called as sequential searching.
 In this search, start searching a value from starting point of the list to ending point of the list.
 Here, we assume the search value as “key value”.
 Start comparing the key value from the first element of the array to end of the array
sequentially one element after the other. While comparing, if the key value and the element
value are same(equal) then print a message that “key value found”.
 If the key value is not found in the array then display a message like “key value not found in
the array”.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 133
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Example: 0 1 2 3 4
a 6 10 3 15 25

In the above array, we would like to search key=15. The comparison starts from first
element as shown below.
0 1 2 3 4
a 6 10 3 15 25

key
Here, key is not equal to a[0], compare with next element.
0 1 2 3 4
a 6 10 3 15 25

key
Here, key and a[1] are not equal, compare with next element.
0 1 2 3 4
a 6 10 3 15 25

key
Here, key and a[2] are not equal, compare with next element.
0 1 2 3 4
a 6 10 3 15 25

key
Here, key and a[3] values are equal. So the key element is found in the 3rd index position.
Searching is not completed yet, compare with the last element.
0 1 2 3 4
a 6 10 3 15 25

key
Here, key is not equal to a[4]. Now searching is complete. Our key value is found at 3 rd
index position.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 134
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Ex: Program to search a value in the array sequentially Output:


import java.io.*; Enter size of the array
class SeqSearch 5
{ Enter elements into array
public static void main(String args[ ])throws IOException 6
{ 10
DataInputStream dis=new DataInputStream(System.in); 3
int i, n, key, found=0 ; 15
System.out.println("Enter size of the array");
25
n=Integer.parseInt(dis.readLine( ));
Enter search element
int a[ ]=new int[n];
15
System.out.println("Enter elements into array");
Element found at 3 index
for(i=0; i<n; i++)
a[i]=Integer.parseInt(dis.readLine( )); position

System.out.println("Enter element to search");


key=Integer.parseInt(dis.readLine( ));
for(i=0; i<n; i++)
{
if(key= =a[i])
{
System.out.println("Element found at"+i+" index position");
found=1;
}
}
if(found= =0)
System.out.println("Element not found in the array");
}
}
Binary search: Sequential search is easy to write and efficient for short lists, but complex for
large ones. To search an item in a large sorted list, we use binary search. In this we first
compare the item in the center of the list, depending on whether the item comes before or after
the central one. In this way at each step we reduce the length of the list to be searched. In only
twenty comparisons this method will locate any requested item in a list of a millions items.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 135
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Steps:
 First step in binary search is that the list should be properly ordered i.e. sorted into ascending
order.
 Then compare the key element with middle element.
 If both are equal then the number we are searching is found and searching complete,
otherwise continue searching.
 If key is not equal to the middle element then see whether the key is less than or greater than
the middle element.
 If the key is less than middle element then the key can be found left side of middle element.
Since we take the left side list which is less than middle element.
 If the key is greater than the middle element then the key can be found right side of middle
element. Since we take the right side list which is greater than middle element.
 Again compare the key value with the middle element in the new list and repeat the same
steps until key is found in the list or list get empty.
Ex: Assume that we want to search the number 60 in the following list of numbers present in
the array, i.e. key=60.
0 1 2 3 4 5 6 7 8 9
a 30 60 10 80 20 100 40 70 50 90

Before we search the number in the array, it should be sorted.


0 1 2 3 4 5 6 7 8 9
a 10 20 30 40 50 60 70 80 90 100

low mid high


here, low=0 and high=9
Now compare the key element with middle element. Middle element can be calculated as
follows
mid = ( low + high)/2
mid = ( 0+9 )/2 = 4.5 = 4
Here, key is not equal to a[mid]=a[4]. And key is greater than a[mid], since the key value
can be found at right side of mid element. Now we get the new array by moving low=mid+1.
The new array is:

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 136


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

5 6 7 8 9
a 60 70 80 90 100

low mid high


mid= (5+9)/2=14/2 = 7
Here, key is not equal to a[mid]=a[7]. And key is less than a[mid], since the key value
can be found at left side of mid element. Now we get the new array by moving high=mid-1.
The new array is:
5 6
a 60 70

low high mid=(5 + 6)/2 = 5.5=5


mid
Here, key is equal to a[mid]=a[5], so print a message like “element found at 5th index
position”. Continue the process till low and high are crossed each other or terminate the process
once key value is found.
Ex: Program to search an element in the array using binary search.
import java.io.*;
class BinSearch
{
public static void main(String args[ ])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int i, n, key, found=0, low,high,mid ;
System.out.println("Enter size of the array");
n=Integer.parseInt(dis.readLine( ));
int a[ ]=new int[n];
System.out.println("Enter elements in sorted order");
for(i=0; i<n; i++)
a[i]=Integer.parseInt(dis.readLine( ));
System.out.println("Enter element to search");
key=Integer.parseInt(dis.readLine( ));
low = 0;
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 137
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

high = n-1;
mid = (low+high)/2;
while( low <= high)
{
if ( key= =a[mid])
{
System.out.println("Element found at"+mid+" index position");
found = 1; Output:
break; Enter size of the array
} 10
else if( key<a[mid] )
Enter elements in sorted order
{
10
high = mid-1;
20
}
30
else if( key>a[mid] )
{ 40

low = mid+1; 50
} 60
mid = (low+high)/2; 70
} 80
if ( found= =0) 90
System.out.println(" element not found"); 100
} Enter searching element
} 60
Element found at 5 index position
Q: What is sorting? What are different sorting techniques?
A: Sorting is a process used to arrange the array elements in a specific order i.e. either
ascending or descending. There are several techniques:
i) Bubble sort
ii) Selection sort
iii) Insertion sort
iv) Quick sort
v) Merge sort
vi) Heap sort, etc.
Consider an example: int a[5]={6,4,7,1,5};
After sorting the elements in ascending order, the elements will be: {1, 4, 5, 6, 7}.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 138
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Q: Explain the procedure for bubble sort.


A: The simple and the best known sorting technique is the bubble sort. To sort the sequence
of ‘n’ elements, bubble sort makes ‘n-1’ passes through the data.
 In this sorting technique, compare the first element of the array with the immediately next
element. While comparing arrange the values into Specific order (say, ascending order).
And then compare the first element with the third element and arrange the values into
order.
 This procedure should be continued with remaining elements until first element is
compared with (n-1) element. Now iteration one is completed. After first iteration, the top
most element value gets its proper position.
 Repeat the same procedure for second iteration by comparing second element with
remaining elements. After second iteration the second element gets its proper position.
 Continue the same process until all the elements of the array is sorted.
 Following example shows how bubble sort technique sorts elements in each pass.
6 4 4 1 1 1 1 1 1 1 1 1 1 1

4 6 6 6 6 6 6 4 4 4 4 4 4 4

7 7 7 7 7 7 7 7 7 7 6 5 5 5

1 1 1 4 4 4 4 6 6 6 7 7 7 6

5 5 5 5 5 5 5 5 5 5 5 6 6 7

Iteration-1 Iteration-2 Iteration-3 Iteration-4


In the above example, in 4th iteration, the array is sorted.
Program to implement Bubble sort.
import java.io.*;
class BubbleSort
{
public static void main(String args[ ]) throws Exception
{
DataInputStream dis=new DataInputStream(System.in);

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 139


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

int i, j, n, temp;
System.out.println("How many values:");
n=Integer.parseInt(dis.readLine( ));
int a[ ]=new int[n];
System.out.println("Enter Values:");
for(i=0; i<n; i++)
a[i]=Integer.parseInt(dis.readLine( ));
for(i=0; i<n-1; i++)
for(j=i+1; j<n; j++)
if(a[i]>a[j])
{
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
System.out.println("After Sorting:");
for(i=0; i<n; i++)
System.out.print("\t"+a[i]);
}
}
Save: BubbleSort.java
Compilation: javac BubbleSort.java
Execution: java BubbleSort
Output: How many values:
5
Enter Values:
12
4
16
8
20
After Sorting: 4 8 12 16 20

Q: Explain the procedure for insertion sort?


A: Insertion sort is a simple sorting algorithm, a comparison sort in which the sorted array is
built one entry at time. It provides several advantages.
i) It is simple to implement.
ii) It is efficient for small data sets.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 140
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Procedure:
 In this technique, take any element (key), compare with its previous elements until it
finds the key element value is greater than other element.
 If key element value is less than the other element, then swap them.
 This procedure should be continued until all elements in the array are sorted.
6 4 4 4 4 4 4 1 1 1 1

4 6 6 6 6 6 1 4 4 4 4

7 7 7 7 7 1 6 6 6 6 5

1 1 1 1 1 7 7 7 7 5 6

5 5 5 5 5 5 5 5 5 7 7

Iteration-1 Iteration-2 Iteration-3 Iteration-4


(key = 4) (key = 7) (key = 1) (key = 5)

Program to implement Insertion sort.


import java.io.*;
class InsSort
{
public static void main(String args[ ]) throws Exception
{
DataInputStream dis=new DataInputStream(System.in);
int i, j, n, t;
System.out.println("How many values:");
n=Integer.parseInt(dis.readLine( ));
int a[ ]=new int[n];
System.out.println("Enter Values:");
for(i=0; i<n; i++)
a[i]=Integer.parseInt(dis.readLine( ));
for(i=1; i<n; i++)
{
t=a[i];
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 141
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

for(j=i; j>0; j- -)
{
if(t<a[j-1])
a[j]=a[j-1];
else
break;
}
a[j]=t;
}
System.out.println("After Sorting");
for(i=0; i<n; i++)
System.out.print("\t"+a[i]);
}
}
Save: InsSort.java
Compilation: javac InsSort.java
Execution: java InsSort
Output: How many values:
5
Enter Values:
24
65
12
36
42
After Sorting 12 24 36 42 65
Q: Explain the procedure for selection sort.
A: It is efficient on large lists, and generally performs worse than insertion sort. The
selection sort performs the same number of comparisons as the bubble sort: n*(n-1)/2.
Procedure:
 In this sorting technique, first element value is considered as minimum and this minimum
value is compared with remaining elements of the same array.
 While comparing, if you find the index whose value is less than the first element and
minimum of remaining elements, then swap the values. After swapping the first element
got the proper position.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 142


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

 Now take the second element as minimum value and compared with remaining elements
and you finds the index whose value is less than second element and minimum of
remaining elements, and then swap them.
 The same procedure continued until all elements are sorted.
6 6 6 6 1 1 1 1 1 1 1 1

4 4 4 4 4 4 4 4 4 4 4 4

7 7 7 7 7 7 7 7 7 7 7 5

1 1 1 1 6 6 6 6 6 6 6 6
5 5 5 5 5 5 5 5 5 5 5 7

Iteration -1 Iteration-2 Iteration-3


(min = 6) (min = 4) (min = 7)

Program to implement Selection sort.


import java.io.*;
class SelSort
{
public static void main(String args[ ]) throws Exception
{
DataInputStream dis=new DataInputStream(System.in);
int i, j, k, n, t, max;
System.out.println("How many values:");
n=Integer.parseInt(dis.readLine( ));
int a[ ]=new int[n];
System.out.println("Enter Values:");
for(i=0; i<n; i++)
a[i]=Integer.parseInt(dis.readLine( ));
for(i=0; i<n-1; i++)
{
max=a[i];
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 143
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

k=i;
for(j=i+1; j<n; j++)
{
if(a[j]<min)
{
min= a[j];
k= j;
}
}
t= min;
a[k]= a[i];
a[i]= t;
}
System.out.println("After Sorting:");
for(i=0; i<n; i++)
System.out.print("\t"+a[i]);
}
}
Save: SelSort.java
Compilation: javac SelSort.java
Execution: java SelSort
Output: How many values:
5
Enter Values:
50
30
10
20
40
After Sorting: 10 20 30 40 50

Q: Explain the procedure for Quick sort?


A: Quick sort is significantly faster than other algorithms like bubble sort, because its inner
loop can be efficiently implemented on most architectures.
It uses “divide and conquer” strategy to divide a list into two sub lists. Quick sort is also
known as “Partition-Exchange sort”.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 144
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Procedure:
 Pick an element, called a “pivot” from the list (here we are choosing last element).
 Reorder the list so that all elements which are less than the pivot come before the pivot
element and the elements greater than pivot comes after it.
 After this partitioning, the pivot is in its proper position.
 Recursively sort the sub-list of lesser elements and the sub-lists of greater elements.
Example: The quick sort takes the last element (9) and places it such that all the numbers in the
left sub-list are smaller and all the numbers in the right sub-list are bigger. It then quick sorts
the left sub-list ({1}) and then quick sorts the right sub-list ({63, 72, 64, 58, 14, 27}) in similar
fashion. This is a recursive algorithm, since it is defined in terms of itself. This reduces the
complexity of programming.
Initial Data 27 63 1 72 64 58 14 9
1st pass 1 <9> 63 72 64 58 14 27
63 72 64 58 14 27
14 < 27 > 72 64 58 63
2nd pass 1 9 14 27 72 64 58 63
72 64 58 63
58 < 63 > 64 72
3rd pass 1 9 14 27 58 63 64 72
(Note: Refer practical program no:18)

Q: Explain the procedure for Merge sort?


A: Merge sort is a divide and conquer algorithm.
Steps to implement Merge Sort:
1) Divide the unsorted array into n partitions, each partition contains 1 element. Here the one
element is considered as sorted.
2) Repeatedly merge partitioned units to produce new sublists until there is only 1 sublist
remaining. This will be the sorted list at the end.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 145
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

(Note: Refer Practical program no:17)

Q: What is Heap? Explain its implementation.


A: In computer science, a heap is a specialized tree-based data structure that satisfies the
heap property: if P is a parent node of C, then the key (the value) of node P is greater than the
key of node C. A common implementation of a heap is the binary heap, in which the tree is a
complete binary tree.
A Complete binary tree is a binary tree in which every node other than the leaves has two
children. In complete binary tree at every level, except possibly the last, is completely filled,
and all nodes are as far left as possible.
Let's understand with simple words now,
 If a Binary Tree is filled level by level, left to right (Left child followed by Right child.)
then it is called complete binary tree.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 146
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

 If Right child is present without Left child then it is not complete.


Depending on the ordering, a heap is called a max-heap or a min-heap.
 In a Max-heap, the keys of parent nodes are always greater than or equal to those of the
children. In max-heap, Largest element of the Tree is always at top(Root Node).
 In a Min-heap, the keys of parent nodes are less than or equal to those of the children.
In min-heap, Smallest element of the Tree is always at top(Root Node).

Implementation of Max Heap:


Let’s assume that we have a heap having some elements which are stored in array Arr.
The way to convert this array into a heap structure is the following. We pick a node in the array,
check if the left sub-tree and the right sub-tree are max heaps, in themselves and the node itself
is a max heap (it’s value should be greater than all the child nodes).
To do this we will implement a function that can maintain the property of max heap (i.e
each element value should be greater than or equal to any of its child and smaller than or equal
to its parent)
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 147
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

void max_heapify (int Arr[ ], int i, int N)


{
int left = 2*i //left child
int right = 2*i +1 //right child
if(left<= N and Arr[left] > Arr[i] )
largest = left;
else
largest = i;
if(right <= N and Arr[right] > Arr[largest] )
largest = right;
if(largest != i )
{
swap (Ar[i] , Arr[largest]);
max_heapify (Arr, largest,N);
}
}
Example: In the diagram below,initially 1st node (root node) is violating property of max-heap
as it has smaller value than its children, so we are performing max_heapify function on this
node having value 4.

As 8 is greater than 4, then 8 is swapped with 4 and max_heapify is performed again on


4, but on different position. Now in step 2, 6 is greater than 4, so 4 is swapped with 6 and we
will get a max heap, as now 4 is a leaf node, so further call to max_heapify will not create any
effect on heap.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 148
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Implementation of Min Heap:


Let’s assume that we have a heap having some elements which are stored in array Arr.
The way to convert this array into a heap structure is the following. We pick a node in the array,
check if the left sub-tree and the right sub-tree are min heaps, in themselves and the node itself
is a min heap (it’s value should be less than all the child nodes).
To do this we will implement a function that can maintain the property of min heap (i.e
each element value should be less than or equal to any of its child and greater than or equal to
its parent).
void min_heapify (int Arr[ ] , int i, int N)
{
int left = 2*i;
int right = 2*i+1;
int smallest;
if(left <= N and Arr[left] < Arr[ i ] )
smallest = left;
else
smallest = i;
if(right <= N and Arr[right] < Arr[smallest] )
smallest = right;
if(smallest != i)
{
swap (Arr[ i ], Arr[ smallest ]);
min_heapify (Arr, smallest,N);
}
}
Example: Suppose you have elements stored in array Arr {4, 5, 1, 6, 7, 3, 2}. As you can see in
the diagram below, the element at index 1 is violating the property of min -heap, so performing
min_heapify(Arr, 1) will maintain the min-heap.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 149


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Q: Explain the procedure for Heap sort?


A: Before going into Heapsort algorithm, Let's understand few points,If we have an array say
[4, 10, 3, 5, 1], then we can represent array as complete binary tree(start adding nodes from
left to right) like shown below.

Algorithm:
STEP 1: Logically, think the given array as Complete Binary Tree.
STEP 2: For sorting the array in ascending order, check whether the tree is satisfying Max-
heap property at each node, (For descending order, Check whether the tree is satisfying Min-
heap property).Here we will be sorting in Ascending order.
STEP 3: If the tree is satisfying Max-heap property, then largest item is stored at the root of the
heap. (At this point we have found the largest element in array, Now if we place this element at
the end(nth position) of the array then 1 item in array is at proper place).We will remove the
largest element from the heap and put at its proper place(nth position)inarray.
After removing the largest element, which element will take its place?
We will put last element of the heap at the vacant place. After placing the last element at
the root, The new tree formed may or may not satisfy max-heap property. So, If it is not
satisfying max-heap property then first task is to make changes to the tree, So that it satisfies
max-heap property.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 150


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

(Heapify process: The process of making changes to tree so that it satisfies max-heap
property is called heapify). When tree satisfies max-heap property, again largest item is stored
at the root of the heap. We will remove the largest element from the heap and put at its proper
place(n-1 position) in array.
Repeat step 3 until size of array is 1 (At this point all elements are sorted.)

After all the steps, we will get a sorted array.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 151


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

(Note: Refer Practical program no:19)

Q: Discuss about comparision of sorting techniques.


A: All sorting algorithms share the goal of outputting a sorted list, but the way that each
algorithm goes about this task can vary. When working with any kind of algorithm, it is
important to know how fast it runs and in how much space it operates in other words, its time
complexity and space complexity.
There are many different sorting algorithms, with various pros and cons. Here are a few
examples of common sorting algorithms.
Merge Sort: Mergesort is a comparison-based algorithm that focuses on how to merge together
two pre-sorted arrays such that the resulting array is also sorted.
Insertion Sort: Insertion sort is a comparison-based algorithm that builds a final sorted array
one element at a time. It iterates through an input array and removes one element per iteration,
finds the place the element belongs in the array, and then places it there.
Bubble Sort: Bubble sort is a comparison-based algorithm thatcompares each pair of elements
in an array and swaps them if they are out of order until the entire array is sorted. For each
element in the list, the algorithm compares every pair of elements.
Quicksort: Quicksort is a comparison-based algorithm that uses divide-and-conquer to sort an
array. The algorithm picks a pivot element, , and then rearranges the array into two subarrays ,
such that all elements are less than , and , such that all elements are greater than or equal to .
Heapsort: Heapsort is a comparison-based algorithm that uses a binary heap data structure to
sort elements. It divides its input into a sorted and an unsorted region, and it iteratively shrinks
the unsorted region by extracting the largest element and moving that to the sorted region.
Selection Sort: The idea behind selection sort is that we put a list in order by placing each item
in turn. In other words,we put the smallest item at the start of the list, then the next smallest
item at the second position in the list, and so on until the list is in order.

Q: How do you find efficiency(complexity) of algorithm.


A: The complexity of sorting algorithm is measured by f (n), function on the size of the list
(n is number of elements in the list). Based on the number of comparisons required to sort the
given list.
The following table summarizes the various sorting algorithm in terms of their time and
space complexities.
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 152
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Sorting Case Time complexity Space complexity


Technique
Selection sort Averge O(n2) O(n)

Worst O(n2) O(n)


Bubble sort Average O(n2) O(n)

Worst O(n2) O(n)


Insertion sort Average O(n2) O(n)

Worst O(n2) O(n)

Merge sort Average O(n log n) O(n)

Worst O (n log n) O(n)

Quick sort Average O (n log n) O(n)

Worst O (n2) O(n)


Efficiency of selection sort: Let us now analyze the efficiency of the selection sort. We can
easily understand from the algorithm that is first passed of the program does (n-1) comparisons.
The next pass of the program does (n-2) comparisons and so on. The total number of
comparisons at the end of sort would be:
=(n-1)+(n-2)+(n-3)+…………..+3+2+1.
=n*(n-1)/2
=n2 i.e. Time complexity =O(n2)
Efficiency of Bubble sort: Let us now analyze the efficiency of the bubble sort. We can easily
understand from the algorithm that is first pass of the program does (n-1) comparisons. The next
pass of the program does (n-2) comparisons and so on. The total number of comparisons at the
end of sort would be:
=(n-1)+(n-2)+(n-3)+…………..+3+2+1.
=n*(n-1)/2
=n2 i.e. Time complexity =O(n2)

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 153


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Efficiency of Insertion sort: Let us now analyze the efficiency of the bubble sort. We can
easily understand from the algorithm that is first pass of the program does (n-1) comparisons.
The next pass of the program does (n-2) comparisons and so on. The total number of
comparisons at the end of sort would be:
=(n-1)+(n-2)+(n-3)+…………..+3+2+1.
=n*(n-1)/2
=n2 i.e. Time complexity =O(n2)
Efficiency of Merge sort: It is O(nlogn). Merge sort is a divide and conquer algorithm. Think
of it in terms of 3 steps.
1. The divide step computes the midpoint of each of the sub-arrays. Each of this step just
takes O(1) time.
2. The conquer step recursively sorts two subarrays of n/2 (for even n) elements each.
3. The merge step merges n elements which takes O(n) time.
Now, for steps 1 and 3 i.e. between O(1) and O(n), O(n) is higher. Let's consider steps 1 and
3 take O(n) time in total. Say it is cn for some constant c.
How many times are these steps executed?
For this, look at the tree below - for each level from top to bottom Level 2 calls merge
method on 2 sub-arrays of length n/2 each. The complexity here is 2 * (cn/2) = cn Level 3 calls
merge method on 4 sub-arrays of length n/4 each. The complexity here is 4 * (cn/4) = cn and so
on ...
Now, the height of this tree is (logn + 1) for a given n. Thus the overall complexity is (logn +
1)*(cn). That is O(nlogn) for the merge sort algorithm.

Efficiency of Quick sort:


Worst-case: O(N2): This happens when the pivot is the smallest (or the largest) element. Then
one of the partitions is empty, and we repeat recursively the procedure for N-1 elements.
Best-case & Average-case O(NlogN): The best case is when the pivot is the median of the
array, and then the left and the right part will have same size. There are logN partitions, and to
obtain each partitions we do N comparisons (and not more than N/2 swaps). Hence the
complexity is O(NlogN).

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 154


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Programs for Practical Exam

1. A program to demonstrate visibility control in Java

2. A program to demonstrate polymorphism in Java.

3. A Program to demonstrate Multilevel inheritance

4. A program to demonstrate String and StringBuffer classes

5. A program to demonstrate Exception Handling

6. A program to perform matrix multiplication

7. A program to implement stack ADT using array.

8. A program to convert infix expression to postfix expression

9. A program to evaluate postfix expression

10.A program to implement towers of Hanoi problem

11.A program to implement Queue ADT using Array

12.A program to create single linked list and perform insert, delete operations

13.A program to create double linked list and perform insert, delete operations

14.A program to implement circular queue using array method

15.A program to implement circular queue using linked list

16.A program to implement binary tree and its traversals

17.A program to implement merge sort

18.A program to implement quick sort

19.A program to implement Heap sort

20.A program to implement linear and binary search on strings

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 155


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

1. A program to demonstrate visibility control in Java.


Access modifiers in Java helps to restrict the scope of a class, constructor , variable , method
or data member. There are four types of access modifiers available in java:
1. Default – No keyword required
2. Private
3. Protected
4. Public

Default:
class Geek
{
void display( )
{
System.out.println("Hello World!");
}
}

class DefDemo Save: DefDemo.java


{
public static void main(String args[ ]) Compilation: javac DefDemo.java
{ Execution: java DefDemo
Geek obj = new Geek( );
obj.display( ); Output: Hello World!
}
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 156
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Private:
class A
{
private void display( )
{
System.out.println("It is a private method");
}
}
class PriDemo
{
public static void main(String args[ ])
{
A obj = new A( );
//trying to access private method of another class
obj.display( );
}
}
Save: PriDemo.java
Compilation: javac PriDemo.java
PriDemo.java:14: display( ) has private access in A
obj.display();
^
1 error

Protected:
class Alpha
{
protected void display( )
{
System.out.println("This method is protected");
}
}
class Beta extends Alpha
{
public void show( )
{
System.out.println("Hello");
}
}
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 157
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

class ProtDemo
{ Save: ProtDemo.java
public static void main(String args[ ]) Compilation: javac ProtDemo.java
{
Beta obj = new Beta( ); Execution: java ProtDemo
obj.display( ); Output: This method is protected
obj.show( );
} Hello

}
Public:
class X
{
public void display( )
{
System.out.println("Iam Saying...");
}
}
class Y extends X
{
public void show( )
{
System.out.println("Hello");
}
}
class PubDemo Save: PubDemo.java
{
public static void main(String args[ ]) Compilation: javac PubDemo.java
{ Execution: java PubDemo
Y obj = new Y( );
obj.display( ); Output: Iam Saying...
obj.show( ); Hello
}
}
2. A program to demonstrate polymorphism in Java.
Static Polymorphism:
class Calc
{
public void sum (int x, int y)

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 158


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

{
System.out.println(“Sum=”+(x+y));
}
public void sum (double x, double y)
{
System.out.println(“Sum=”+(x+y));
}
public void sum (int x, int y, int z)
{
System.out.println(“Sum=”+(x+y+z));
}
}
class MethOverLoad Save: MethOverLoad.java
{ Compilation: javac MethOverLoad.java
public static void main(String args[ ])
{ Execution: java MethOverLoad
Calc c1= new Calc( ); Output: Sum=29
c1.sum(9, 20);
c1.sum(10.5, 22.5); Sum=33.0
c1.sum(9, 20, 11); Sum=40
}
}

Dynamic Polymorphism:
class One
{
public void show( )
{
System.out.println(“This is parent class”);
}
}
class Two extends One
{
public void show( )
{
System.out.println(“This is child class”);
}
}
class MethodOverRide
{

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 159


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

public static void main(String args[ ]) Save: MethodOverRide.java


{ Compilation: javac MethodOverRide.java
Two t= new Two( ); Execution: java MethodOverRide
t.show( ); Output: This is child class
t.show( ); This is child class
}
}
3. A program to demonstrate MultiLevel Inheritance.
class Alpha
{
public void show( )
{
System.out.println(“Hello Alpha”);
}
}
class Beta extends Alpha
{
public void display( )
{
System.out.println(“Hello Beta”);
}
}
class Gamma extends Beta
{
public void show2( )
{
System.out.println(“Hello Gamma”);
}
}
class MultiLevelInh Save: MultiLevelInh.java
{
public static void main(String args[ ]) Compilation: javac MultiLevelInh.java
{ Execution: java MultiLevelInh
Gamma g= new Gamma( );
g.show( ); Output: Hello Alpha
g.display( ); Hello Beta
g.show2( );
} Hello Gamma
}
4. A program to demonstrate String and StringBuffer classes.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 160


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

String class:
import java.io.*;
class StringTest
{
public static void main(String args[ ])
{
String s1="abc", s2="xyz";
System.out.println("Length:" +s1.length( ));
System.out.println("Concatenation:" +s1.concat(s2));
System.out.println("Uppercase:" +s1.toUpperCase( ));
System.out.println("Lowercase:" +s1.toLowerCase( ));
System.out.println("Substring(1,2):" +s1.substring(1,2));
System.out.println("Replace:" +s1.replace('c', 'v'));
System.out.println("Character at position 2:" +s1.charAt(2));
int k= s1.compareTo(s2);
if(k>0)
System.out.println(s1+ "is big");
else if(k<0)
System.out.println(s2 + "is big");
else
System.out.println(s1 + "and" + s2 + "are equal");
if(s1.equals(s2))
System.out.println(s1 + "and" + s2 + "are equal");
else
System.out.println(s1 + "and" + s2 + "are not equal");
if(s1.equalsIgnoreCase(s2))
System.out.println(s1 + "and" + s2 + "are equal");

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 161


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

else
System.out.println(s1 + "and" + s2 + "are not equal");
}
}
Save: StringTest.java
Compilation: javac StringTest.java
Execution: java StringTest
Output: Length:3
Concatenation:abcxyz
Uppercase:ABC
Lowercase:abc
Substring(1,2):b
Replace:abv
Character at position 2:c
xyzis big
abcandxyzare not equal
abcandxyzare not equal
StringBuffer:
class StringBufferTest
{
public static void main(String args[ ])
{
String s1=new String("MADAM");
StringBuffer dup=new StringBuffer(s1);
String s2= dup.reverse( ).toString( );
if(s1.equalsIgnoreCase(s2))
System.out.println(s1 + "is palindrome");
else
System.out.println(s1 + "is not palindrome");
}
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 162


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Save: StringBufferTest.java
Compilation: javac StringBufferTest.java
Execution: java StringBufferTest
Output: MADAM is palindrome
5. A program to demonstrate Exception Handling.
class ExceptHand
{
public static void main(String args[ ])
{
int a=10, b=5, c=5, x, y;
try
{
x = a / (b-c);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
finally
{
y = a / (b+c);
System.out.println("y="+y);
}
}
}
Save: ExceptHand.java
Compilation: javac ExceptHand.java
Execution: java ExceptHand
Output: Division by zero
y=1
6. A program to perform matrix multiplication.
import java.io.*;
class MatrixMulti
{
public static void main(String args[ ])throws IOException
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 163
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

{
DataInputStream dis=new DataInputStream(System.in);
int m, n, p, q, i, j, k;
System.out.println("Enter size of 1st matrix:");
m= Integer.parseInt(dis.readLine());
n= Integer.parseInt(dis.readLine());
System.out.println("Enter size of 2nd matrix:");
p= Integer.parseInt(dis.readLine());
q= Integer.parseInt(dis.readLine());
if(n != p)
{
System.out.println("Mltiplication not possible");
}
else
{
int a[ ][ ]= new int[m][n];
int b[ ][ ]= new int[p][q];
int c[ ][ ]= new int[m][q];
System.out.println("Enter values into 1st matrix:");
for(i=0; i<m; i++)
for(j=0; j<n; j++)
a[i][j]= Integer.parseInt(dis.readLine());
System.out.println("Enter values into 2nd matrix:");
for(i=0; i<p; i++)
for(j=0; j<q; j++)
b[i][j]= Integer.parseInt(dis.readLine());
for(i=0; i<m; i++)
for(j=0; j<q; j++)
{
c[i][j]= 0;
for(k=0; k<n; k++)
c[i][j] = c[i][j]+ a[i][k]*b[k][j];
}
System.out.println("Matrix multiplication is:");
for(i=0; i<m; i++)
{
System.out.println(" ");
for(j=0; j<q; j++)
System.out.print("\t"+ c[i][j]);
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 164


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

}
}
}
Save: MatrixMulti.java
Compilation: javac MatrixMulti.java
Execution: java MatrixMulti
Output: Enter size of 1st matrix:
3
3
Enter size of 2nd matrix:
3
3
Enter values into 1st matrix:
1
2
3
1
2
3
1
2
3
Enter values into 2nd matrix:
1
2
3
1
2
3
1
2
3
Matrix multiplication is:
6 12 18
6 12 18
6 12 18
7. A program to implement stack ADT using array.
class Stack
{
private static int MAX=5;

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 165


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

private int a[ ]=new int[MAX];


int top;
Stack( )
{
top= -1;
}
public void push(int v)
{
if(top>=MAX)
System.out.println("Stack is full");
else
{
top++;
a[top]=v;
}
}
public void pop( )
{
if(top= = -1)
System.out.println("Stack is empty");
else
{
System.out.println("Element deleted is:"+a[top]);
top- -;
}
}
public void display( )
{
if(top= = -1)
System.out.println("Stack is empty");
else
{
System.out.println("Stack elements:");
for(int i=top; i>=0; i- -)
System.out.println(a[i]);
}
}
}
class StackArray
{

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 166


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

public static void main(String args[ ]) Save: StackArray.java


{ Compilation: javac StackArray.java
Stack s=new Stack( ); Execution: java StackArray
s.push(30); Output: Stack elements:
s.push(40); 50
s.push(50); 40
s.display( ); 30
s.pop( ); Element deleted is:50
s.display( ); Stack elements:
} 40
} 30
8. A program to convert infix expression to postfix expression.
import java.util.Scanner;
import java.util.Stack;
public class InfixToPostfix
{
private boolean isOperator(char c)
{
if(c == '+' || c == '-' || c == '*' || c =='/' || c == '^')
return true;
return false;
}
private boolean checkPrecedence(char c1, char c2)
{
if((c2 == '+' || c2 == '-') && (c1 == '+' || c1 == '-'))
return true;
else if((c2 == '*' || c2 == '/') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/'))
return true;
else if((c2 == '^') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/'))
return true;
else
return false;
}
public String convert(String infix)
{
System.out.printf("%-8s%-10s%-15s\n", "Input","Stack","Postfix");
String postfix = ""; //equivalent postfix is empty initially
Stack<Character> s = new Stack( ); //stack to hold symbols
s.push('#'); //symbol to denote end of stack

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 167


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

System.out.printf("%-8s%-10s%-15s\n", "",format(s.toString( )),postfix);


for(int i = 0; i < infix.length( ); i++)
{
char inputSymbol = infix.charAt(i); //symbol to be processed
if(isOperator(inputSymbol))
{ //if a operator
//repeatedly pops if stack top has same or higher precedence
while(checkPrecedence(inputSymbol, s.peek( )))
postfix += s.pop();
s.push(inputSymbol);
}
else if(inputSymbol == '(')
s.push(inputSymbol); //push if left parenthesis
else if(inputSymbol == ')')
{
//repeatedly pops if right parenthesis until left parenthesis is found
while(s.peek( ) != '(')
postfix += s.pop( );
s.pop( );
}
else
postfix += inputSymbol;
System.out.printf("%-8s%-10s%-15s\n", ""+inputSymbol,format(s.toString( )),postfix);
}
//pops all elements of stack left
while(s.peek( ) != '#')
{
postfix += s.pop( );
System.out.printf("%-8s%-10s%-15s\n", "",format(s.toString( )),postfix);
}
return postfix;
}
private String format(String s)
{
s = s.replaceAll(",",""); //removes all , in stack string
s = s.replaceAll(" ",""); //removes all spaces in stack string
s = s.substring(1, s.length( )-1); //removes [ ] from stack string
return s;
}
public static void main(String[ ] args)

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 168


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

{
InfixToPostfix obj = new InfixToPostfix( );
Scanner sc = new Scanner(System.in);
System.out.print("Infix : \t");
String infix = sc.next( );
System.out.print("Postfix : \t"+obj.convert(infix));
}
}
Save: InfixToPostfix.java
Compilation: javac InfixToPostfix.java
Execution: java InfixToPostfix
Output: Infix : (a+b)*c+d*e
Input Stack Postfix
#
( #(
a #( a
+ #(+ a
b #(+ ab
) # ab+
* #* ab+
c #* ab+c
+ #+ ab+c*
d #+ ab+c*d
* #+* ab+c*d
e #+* ab+c*de
#+ ab+c*de*
# ab+c*de*+
Postfix : ab+c*de*+
9. A program to evaluate postfix expression.
import java.io.*;
import java.util.*;
class Stack
{
private int a[ ]=new int[20];
int top;
Stack( )
{
top=0;
}
public void push(int v)

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 169


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

{
if(top<20)
a[top++]=v;
else
System.out.println("Overflow");
}
public int pop( )
{
if(top>0)
return a[- -top];
else
{
System.out.println("Underflow");
return -1;
}
}
public boolean isEmpty( )
{
return top==0;
}
}
class PostFix
{
public static void main(String args[ ]) throws Exception
{
DataInputStream dis=new DataInputStream(System.in);
int a, b, c=0;
String str, s;
Stack s1=new Stack( );
int i;
System.out.print("Enter Postfix expression:");
str=dis.readLine( );
StringTokenizer st=new StringTokenizer(str,",");
while(st.hasMoreTokens( ))
{
s=st.nextToken( );
if(("+-*/").indexOf(s)>=0)
{
b= s1.pop( );
a= s1.pop( );

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 170


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

switch(s.charAt(0)) Save: Postfix.java


{ Compilation: javac Postfix.java
case '+': c=a+b;
break; Execution: java Postfix
case '-': c=a-b; Output: Enter Postfix expression:2,3,*,4,2,/,+
break; Result=8
case '*': c=a*b;
break;
case '/': c=a/b;
break;
}
s1.push(c);
}
else
s1.push(Integer.parseInt(s));
}
System.out.println("Result="+s1.pop( ));
}
}
10.A program to implement towers of Hanoi problem.
The 'Towers of Hanoi' is a classical problem used to illustrate the power of recursion. The
puzzle goes as follows.
There are three poles and 64 discs of different sizes. Initially, all the discs are placed on
the first pole with the largest disc at the bottom and the smallest one at the top. We need to
move all the discs from the first pole to the third pole, with the smallest disc at the top and the
largest at the bottom. We can move only one disc at a time (which should be the topmost disc)
and at any point of time, a larger disc cannot be placed over a smaller one i.e. all the discs on a
pole must be placed in such a way that the smallest is at the top and the largest at the bottom.
The second pole can be used as an intermediate pole to help us in transferring the discs.
This puzzle can be solved using recursion. For a moment, assume that there are just two
discs (disc 1 and 2; disc 2 being the larger one) on the first pole. The solution consists of three
steps.
Step 1: Move disc 1 from pole 1 to pole 2.
Step 2: Move disc 2 from pole 1 to pole 3.
Step 3: Move disc 1 from pole 1 to pole 3.
Now, assume that disc 1 is not a single disc but a collection of discs. The procedure
would be similar to the above three steps, but steps 1 and 3 would be a collection of steps. Step

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 171


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

1 would be to move the n-1 discs (assuming that there were a total of n discs) from pole 1 to
pole 2. For moving these (n -1) discs, we again follow the same strategy of considering them as
1 disc plus a set of n-2 discs. Step 3 would also be similar. This gives us the recursive solution.
Recursive Algorithm: The recursive solution to move n discs from the start pole to the
end pole using an auxiliary pole is given below.
Base Case - When n = 1
Move the disc from start pole to end pole
Recursive Case - When n > 1
Step 1: Move (n-1) discs from start pole to auxiliary pole.
Step 2: Move the last disc from start pole to end pole.
Step 3: Move the (n-1) discs from auxiliary pole to end pole.
Steps 1 and 3 are recursive invocations of the same procedure.
Program:
import java.io.*;
public class TowersOfHanoi
{
public void solve(int n, String start, String auxiliary, String end)
{
if (n = = 1)
{
System.out.println(start + " -> " + end);
}
else
{
solve(n - 1, start, end, auxiliary);
System.out.println(start + " -> " + end);
solve(n - 1, auxiliary, start, end);
}
}
public static void main(String[ ] args)
{
TowersOfHanoi towersOfHanoi = new TowersOfHanoi( );
System.out.print("Enter number of discs: ");
Scanner scanner = new Scanner(System.in);
int discs = scanner.nextInt( );
towersOfHanoi.solve(discs, "A", "B", "C");
}
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 172


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Save: TowersOfHanoi.java
Compilation: javac TowersOfHanoi.java
Execution: java TowersOfHanoi
Output: Enter number of discs: 3
A -> C
A -> B
C -> B
A -> C
B -> A
B -> C
A -> C
11.A program to implement Queue ADT using Array.
class Queue
{
private static int MAX=10;
private int a[ ]=new int[MAX];
int front, rear;
Queue( )
{
front= rear = -1;
}
public void insert(int v)
{
if(rear<MAX)
{
rear++;
a[rear]=v;
}
else
System.out.println("Queue is full");
}
public void del( )
{
if(rear= = -1)
System.out.println("Queue is empty");
else
{
front++;
System.out.println("Element deleted is:"+a[front]);
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 173


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

}
public void display( )
{
if(rear= = -1)
System.out.println("Queue is empty");
else
{
System.out.println("Queue elements:");
for(int i=front+1; i<=rear; i++)
System.out.println(a[i]);
}
}
}
class QArray
{ Save: QArray.java
public static void main(String args[ ]) Compilation: javac QArray.java
{ Execution: java QArray
Queue q=new Queue( ); Output: Queue elements:
q.insert(30); 30
q.insert(40); 40
q.insert(50); 50
q.display( ); Element deleted is:30
q.del( ); Queue elements:
q.display( ); 40
} 50
}
12.A program to create single linked list and perform insert, delete operations.
import java.io.*;
class node
{
public int x;
public node next;
}
class LinkedList
{
public node first;
LinkedList( )
{
first = new node( );
first.next= null;

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 174


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

}
void add (int v)
{
node temp=new node( );
temp.x= v;
temp.next= null;
node ptr=first;
while(ptr.next!=null)
ptr= ptr.next;
ptr.next= temp;
}
void insert(int p, int v)
{
node ptr= first,temp;
for(int i=1; i<=p-1; i++)
ptr= ptr.next;
temp= new node( );
temp.x= v;
temp.next= ptr.next;
ptr.next= temp;
}
void del(int p)
{
node ptr= first,temp;
for(int i=1; i<=p-1; i++)
ptr=ptr.next;
temp= ptr.next;
ptr.next= ptr.next.next;
temp= null;
}
void show( )
{
System.out.println("\nList Elements:");
for(node ptr=first.next; ptr!=null; ptr=ptr.next)
System.out.print("\t"+ptr.x);
}
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 175


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

class SListTest
{
public static void main(String args[ ]) throws Exception
{
DataInputStream dis=new DataInputStream(System.in);
String con=" ";
int x, op, p, v;
LinkedList L1=new LinkedList( );
System.out.println("Enter elements to create");
do
{
x=Integer.parseInt(dis.readLine( ));
L1.add(x);
System.out.print("Add more?(y,n):");
con=dis.readLine( );
}while(con.equalsIgnoreCase("y"));
L1.show();
do
{
System.out.println("\n 1.Insert\n 2.Delete \n 3.Display \n 4.Exit");
System.out.println("\nSelect an option:");
op=Integer.parseInt(dis.readLine( ));
if(op= =1)
{
System.out.println("Enter Position to insert:");
p= Integer.parseInt(dis.readLine( ));
System.out.println("Enter Value to insert:");
v= Integer.parseInt(dis.readLine( ));
L1.insert(p,v);
}
if(op= =2)
{
System.out.println("Enter Position to delete:");
p= Integer.parseInt(dis.readLine( ));
L1.del(p);
}
L1.show( );
}while(op<4);
}
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 176


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Save: SListTest.java
Compilation: javac SListTest.java
Execution: java SListTest
Output: Enter elements to create
10
Add more?(y,n):y
20
Add more?(y,n):y
40
Add more?(y,n):y
50
Add more?(y,n):n
List Elements:
10 20 40 50
1.Insert
2.Delete
3.Display
4.Exit
Select an option: 1
Enter Position to insert: 3
Enter Value to insert: 30
List Elements:
10 20 30 40 50
1.Insert
2.Delete
3.Display
4.Exit
Select an option: 2
Enter Position to delete: 5
List Elements:
10 20 30 40
1.Insert
2.Delete
3.Display
4.Exit
Select an option: 4
List Elements:
10 20 30 40

13.A program to create double linked list and perform insert, delete operations.

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 177


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

import java.io.*;
class node
{
public int x;
public node next;
public node prev;
}
class DoubleLinkedList
{
public node first;
public node last;
DoubleLinkedList( )
{
first= new node( );
first.next= null;
first.prev= null;
last= first;
}
void add (int v)
{
node temp= new node( );
temp.x= v;
temp.next= null;
last.next= temp;
temp.prev= last;
last= temp;
}
void insert(int p, int v)
{
node ptr= first,temp;
for(int i=1; i<=p-1; i++)
ptr= ptr.next;
if(ptr.next= =null)
add(v);
else
{
temp= new node( );
temp.x= v;
temp.next= ptr.next;
ptr.next.prev= temp;

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 178


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

ptr.next= temp;
temp.prev= ptr;
}
}
void del(int p)
{
node ptr= first,temp;
for(int i=1; i<=p-1; i++)
ptr= ptr.next;
if(ptr.next.next==null)
{
temp= last;
last= last.prev;
last.next= null;
}
else
{
temp= ptr.next;
ptr.next= ptr.next.next;
ptr.next.prev= ptr;
}
temp=null;
}
void show( )
{
System.out.println("\nList Elements:Left to Right");
for(node ptr=first.next; ptr!=null; ptr=ptr.next)
System.out.print("\t"+ptr.x);
System.out.println("\nList Elements:Right to Left");
for(node ptr=last; ptr.prev!=null; ptr=ptr.prev)
System.out.print("\t"+ptr.x);
}
}
class DListTest
{
public static void main(String args[ ]) throws Exception
{
DataInputStream dis=new DataInputStream(System.in);
String con=" ";
int x, op, p, v;

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 179


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

DoubleLinkedList L1=new DoubleLinkedList( );


System.out.println("Enter elements to create");
do
{
x=Integer.parseInt(dis.readLine( ));
L1.add(x);
System.out.print("Add more?(y,n):");
con=dis.readLine( );
}while(con.equalsIgnoreCase("y"));
L1.show();
do
{
System.out.println("\n 1.Insert\n 2.Delete \n 3.Display \n 4.Exit");
System.out.println("\nSelect an option:");
op=Integer.parseInt(dis.readLine( ));
if(op= =1)
{
System.out.println("Enter Position to insert:");
p= Integer.parseInt(dis.readLine( ));
System.out.println("Enter Value to insert:");
v= Integer.parseInt(dis.readLine( ));
L1.insert(p,v);
}
if(op= =2)
{
System.out.println("Enter Position to delete:");
p= Integer.parseInt(dis.readLine( ));
L1.del(p);
}
L1.show();
}while(op<4);
}
}
Save: DListTest.java
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 180
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Compilation: javac DListTest.java


Execution: java DListTest
Output: Enter elements to create
30
Add more?(y,n):y
40
Add more?(y,n):y
50
Add more?(y,n):n
List Elements:Left to Right
30 40 50
List Elements:Right to Left
50 40 30
1.Insert
2.Delete
3.Display
4.Exit
Select an option: 1
Enter Position to insert: 2
Enter Value to insert: 90
List Elements:Left to Right
30 90 40 50
List Elements:Right to Left
50 40 90 30
1.Insert
2.Delete
3.Display
4.Exit
Select an option: 4
List Elements:Left to Right
30 90 40 50
List Elements:Right to Left
50 40 90 30
14.A program to implement circular queue using array method.
import java.util.Scanner;
class Queue
{
int a[ ];
int front, rear;
Queue( )

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 181


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

{
a = new int [5];
front = rear = -1;
}
Queue(int size)
{
a = new int[size];
front = rear = -1;
}
void insert(int x)
{
int p;
p = (rear+1)% a.length;
if(p = = front)
System.out.println("Queue Overflow ");
else
{
rear = p;
a[rear] = x;
if(front = = -1)
front = 0;
}
}
boolean empty( )
{
if(front = = -1)
return true;
else
return false;
}
int delete( )
{
int x = a[front];
if(front = = rear)
front = rear = -1;
else
front =(front+1)% a.length;
return x;
}
void display( )

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 182


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

{
if(front = = -1)
System.out.println("Queue underflow");
else
{
System.out.println("Elements of Queue are");
int i = front;
while(i != rear)
{
System.out.println(a[i]);
i = (i+1)% a.length;
}
System.out.println(a[i]);
}
}
void destroy( )
{
front = rear= -1;
}

}
public class CircularQueue
{
public static void main(String args[ ])
{
Queue q = new Queue( ); //Queue of size 5
int ch;
Scanner sc =new Scanner(System.in);
do
{
System.out.println("Menu\n1.insert\n2.delete\n3.display\n4.destroy\n5.exit\n");
System.out.println("Enter choice :");
ch=sc.nextInt( );
switch(ch)
{
case 1:
System.out.println("Enter data to insert");
int x=sc.nextInt( );
q.insert(x);
break;

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 183


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

case 2:
if(q.empty( ))
System.out.println("Queue underflow");
else
{
int z =q.delete( );
System.out.println("data deleted =" + z );
}
break;
case 3: q.display( );
break;

case 4: q.destroy( );
break;
case 5: break;
default : System.out.println("Wrong Choice");
}
}while(ch!=5);
}
}
Save: CircularQueue.java
Compilation: javac CircularQueue.java
Execution: java CircularQueue
Output: Menu
1.insert
2.delete
3.display
4.destroy
5.exit
Enter choice : 1
Enter data to insert 10
Menu
1.insert
2.delete
3.display
4.destroy
5.exit
Enter choice : 1
Enter data to insert 20
Menu

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 184


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

1.insert
2.delete
3.display
4.destroy
5.exit
Enter choice : 1
Enter data to insert 30
Menu
1.insert
2.delete
3.display
4.destroy
5.exit

Enter choice : 3
Elements of Queue are
10
20
30
Menu
1.insert
2.delete
3.display
4.destroy
5.exit
Enter choice : 2
data deleted =10
Menu
1.insert
2.delete
3.display
4.destroy
5.exit
Enter choice : 3
Elements of Queue are
20
30
Menu
1.insert
2.delete

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 185


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

3.display
4.destroy
5.exit
Enter choice : 5
15.A program to implement circular queue using linked list method.
class node
{
public int x;
public node next;
}
class CircularQueue
{
public node front, rear;
CircularQueue( )
{
front=rear=null;
}
void insert(int v)
{
node temp=new node( );
temp.x= v;
if(front= =null)
front=rear=temp;
else
{
rear.next=temp;
rear=temp;
}
rear.next=front;
}
int del( )
{
if(front= =null)
{
System.out.println("Queue overflow");
System.exit(1);
}
int v= front.x;
node temp= front;
if(front= =rear)

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 186


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

front=rear=null;
else
{
front=front.next;
rear.next=front;
}
temp= null;
return v;
}
void show( )
{
System.out.println("Circular Queue Elements:");
for(node ptr=front; ptr!=rear; ptr=ptr.next)
System.out.print("\t"+ptr.x);
System.out.print("\t"+rear.x);
}
}
class CQLTest
{
public static void main(String args[ ])
{
CircularQueue q1=new CircularQueue( );
q1.insert(30);
q1.insert(40);
q1.insert(50);
q1.insert(60);
q1.show();
System.out.println("\nDeleted element:"+q1.del( ));
System.out.println("After deleting:");
q1.show( );
}
}
Save: CQLTest.java
Compilation: javac CQLTest.java
Execution: java CQLTest
Output: Circular Queue Elements:
30 40 50 60
Deleted element:30
After deleting:
Circular Queue Elements: 40 50 60

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 187


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

16.A program to implement binary tree and its traversals.


class tree
{
int x;
tree left;
tree right;
}
class BTree
{
private tree t;
BTree( )
{
t=null;
}
public void insert(int v)
{
t=insert(t,v);
}
public void showLVR( )
{
System.out.println("\nLVR :\n");
LVR(t);
}
public void showVLR( )
{
System.out.println("\nVLR :\n");
VLR(t);
}
public void showLRV( )
{
System.out.println("\nLRV :\n");
LRV(t);
}
tree insert(tree t, int v)
{
if(t= =null)
{
t = new tree( );
t.x = v;
t.left = null;

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 188


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

t.right = null;
}
else if(v<t.x)
t.left = insert(t.left, v);
else if(v>t.x)
t.right = insert(t.right, v);
return t;
}
public void LVR(tree t)
{
if(t!=null)
{
LVR(t.left);
System.out.print("\t"+t.x);;
LVR(t.right);
}
}
public void LRV(tree t)
{
if(t!=null)
{
LRV(t.left);
LRV(t.right);
System.out.print("\t"+t.x);
}
}
public void VLR(tree t)
{
if(t!= null)
{
System.out.print("\t"+t.x);
VLR(t.left);
VLR(t.right);
}
}
}
class BTreeTest
{
public static void main(String args[ ])
{

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 189


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

BTree t1=new BTree( ); Save: BTreeTest.java


t1.insert(30); Compilation: javac BTreeTest.java
t1.insert(20); Execution: java BTreeTest
t1.insert(10); Output: LVR :
t1.insert(40); 10 20 30 40
t1.showLVR( ); VLR :
t1.showVLR( ); 30 20 10 40
t1.showLRV( ); LRV :
} 10 20 40 30
}

17.A program to implement merge sort.


public class MyMergeSort
{
private int[ ] array;
private int[ ] t empMergArr;
private int length;
public static void main(String a[ ])
{

int[ ] inputArr = {45,23,11,89,77,98,4,28,65,43};


MyMergeSort mms = new MyMergeSort( );
mms.sort(inputArr);
for(int i: inputArr)
{
System.out.print(i);
System.out.print(" ");
}
}
public void sort(int inputArr[ ])
{
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
}
private void doMergeSort(int lowerIndex, int higherIndex)
{
if (lowerIndex < higherIndex)
{

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 190


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

int middle = lowerIndex + (higherIndex - lowerIndex) / 2;


// Below step sorts the left side of the array
doMergeSort(lowerIndex, middle);
// Below step sorts the right side of the array
doMergeSort(middle + 1, higherIndex);
// Now merge both sides
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex)
{
for (int i = lowerIndex; i <= higherIndex; i++)
{
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex)
{
if (tempMergArr[i] <= tempMergArr[j])
{
array[k] = tempMergArr[i];
i++;
}
else
{
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle)
{
array[k] = tempMergArr[i];
k++;
i++;
}
}
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 191


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

Save: MyMergeSort.java
Compilation: javac MyMergeSort.java
Execution: java MyMergeSort
Output: 4 11 23 28 43 45 65 77 89 98

18.A program to implement quick sort.


import java.io.*;
class QuickSort
{
public static void qsort(int a[ ], int min, int max)
{
int t, v, i, j;
if (max > min)
{
v = a[max];
i = min;
j = max-1;
do
{
while ((a[i]<v)&&i!=0)
i++;
while ((a[j]>v) && j!=0)
j--;
t = a[i];
a[i] = a[j];
a[j] = t;
}while (j > i);
a[j] = a[i];
a[i] = a[max];
a[max] = t;
qsort(a,min,i-1);
qsort(a,i+1,max);
}
}
public static void main(String args[ ]) throws Exception
{
DataInputStream dis=new DataInputStream(System.in);
int i, n;
System.out.println("How many values:");
n=Integer.parseInt(dis.readLine( ));

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 192


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

int a[ ]=new int[n];


System.out.println("Enter Values:");
for(i=0; i<n; i++)
a[i]=Integer.parseInt(dis.readLine( ));
qsort(a,0,n-1);
System.out.println("After Sorting:");
for(i=0;i<n;i++)
System.out.print("\t"+a[i]);
}
}
Save: QuickSort.java
Compilation: javac QuickSort.java
Execution: java QuickSort
Output: How many values:
4
Enter Values:
45
36
87
12
After Sorting: 12 36 45 87

19.A program to implement Heap sort.


import java.util.Scanner;
public class HeapSort
{
private static int N;
public static void sort(int arr[ ])
{
heapify(arr);
for (int i = N; i > 0; i- -)
{
swap(arr,0, i);
N = N-1;
maxheap(arr, 0);
}
}
public static void heapify(int arr[ ])
{
N = arr.length-1;
for (int i = N/2; i >= 0; i--)
Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 193
downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

maxheap(arr, i);
}
/* Function to swap largest element in heap */
public static void maxheap(int arr[ ], int i)
{
int left = 2*i ;
int right = 2*i + 1;
int max = i;
if (left <= N && arr[left] > arr[i])
max = left;
if (right <= N && arr[right] > arr[max])
max = right;

if (max != i)
{
swap(arr, i, max);
maxheap(arr, max);
}
}
/* Function to swap two numbers in an array */
public static void swap(int arr[ ], int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void main(String[ ] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Heap Sort Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt( );
int arr[ ] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt( );
sort(arr);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 194


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

System.out.print(arr[i]+" ");
System.out.println( );
}
}
Save: HeapSort.java
Compilation: javac HeapSort.java
Execution: java HeapSort
Output: Heap Sort Test
Enter number of integer elements
10
Enter 10 integer elements
12 54 26 38 64 28 90 5 10 81
Elements after sorting
5 10 12 26 28 38 54 64 81 90
20.A program to implement linear and binary search on strings.
Linear search:
import java.io.*;
class LinearSearch
{
public void linsearch(String string[ ], String search)
{
int i;
int flag = 0;
for(i = 0; i<10; i++)
{
if (search.equals(string[i]))
{
flag = 1;
break;
}
}
if (flag = =1)
{
System.out.println("Word found at position " +(i+1));
}
else
{
System.out.println("Word not found.");
}
}

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 195


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

public static void main(String args[ ])throws IOException


{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
LinearSearch obj = new LinearSearch( );
System.out.println("Enter any 10 words:");
String enter[ ] = new String[10];
int i;
for (i = 0; i<10; i++)
{
enter[i] = br.readLine( );
}
System.out.println("Enter word to be searched:");
String search1 = br.readLine( );
obj.linsearch(enter, search1);
}
}
Save: LinearSearch.java
Compilation: javac LinearSearch.java
Execution: java LinearSearch
Output: Enter any 10 words:
welcome
to
sri
vaagdevi
degree
college
huzurabad
satavahana
university
karimnagar
Enter word to be searched:
vaagdevi
Word found at position 4
Binary search:
import java.io.*;
public class BinarySearch
{
private static void sort(String[ ] words)
{
int length = words.length;

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 196


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

for(int i=0; i<length; i++)


{
for(int j=i; j<length; j++)
{
if(words[i].compareTo(words[j]) > 0)
{
String temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}
}
private static int bsearch(String word, String[ ] words, int a, int b)
{
if(b <= a)
return -1;
if(b - a = = 1)
return words[a].equals(word) ? a : -1;
int pivot = (a + b)/2;
if(word.compareTo(words[pivot]) < 0)
return bsearch(word, words, 0, pivot);
else if(word.compareTo(words[pivot]) > 0)
return bsearch(word, words, pivot, b);
return pivot;
}
public static void main(String[ ] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[ ] words = new String[10];
System.out.println(“Enter words:\n”);
for(int i=0; i<10; i++)
{
System.out.print("words["+i+"]: ");
words[i] = br.readLine( );
}
System.out.println("After sorting:\n");
sort(words);
for(int i=0; i<10; i++)
{

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 197


downloaded from: www.sucomputersforum.com
Data Structures Using JAVA [ BSc(Computer Science)-II year III semester]

System.out.println("words["+i+"] = " + words[i]);


}
System.out.print("Enter word to search for: ");
String word = br.readLine( );
int index = bsearch(word, words, 0, words.length);
if(index < 0)
System.out.println("not found");
else
System.out.println("found at index " + index);
}
}
Save: BinarySearch.java
Compilation: javac BinarySearch.java
Execution: java BinarySearch
Output: Enter words:
words[0]: welcome
words[1]: to
words[2]: sri
words[3]: vaagdevi
words[4]: degree
words[5]: college
words[6]: huzurabad
words[7]: satavahana
words[8]: university
words[9]: karimnagar
After sorting:

words[0] = college
words[1] = degree
words[2] = huzurabad
words[3] = karimnagar
words[4] = satavahana
words[5] = sri
words[6] = to
words[7] = university
words[8] = vaagdevi
words[9] = welcome
Enter word to search for: vaagdevi
found at index 8

Prepared by G. Veerachary MCA, AP-SET, UGC-NET Page 198

You might also like