DS Unit 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 110

Data Structure

UNIT I
Syllabus
 Object Oriented Concepts Object Oriented Programming- a
new paradigm, Abstraction, forms of Abstraction, OOP
concepts- Classes, Objects, Polymorphism, Data
Encapsulation, Data Hiding, Inheritance
 Analysis of Algorithm Introduction to algorithm design and
Data structures, Comparison of Algorithms, Complexity in
terms of space and time, Calculation of O- notation
 Abstract Data type and its implementation with a Rational
number example
 Searching and Sorting Searching- Linear and Binary Search
 Sorting- Bubble Sort, Selection Sort , Insertion Sort, Quick
Sort
 Merge Sort, Comparison of various searching and sorting
techniques in terms of time complexity
BEGINNING WITH C++
It was developed by Bjarne Stroustrup at AT&T
Bell Laboratories in Murray Hill, New Jersey,
USA, in the early 1980’s.
Stroustrup, an admirer of simula67 and a strong
supporter of C, wanted to combine the best of
both the languages and create a more powerful
language that could support object-oriented
programming features and still retain the power
and elegance of C. The result was C++.
C++ is a superset of C.
KEYWORDS
DATATYPES IN C++
DATATYPES IN C++
Built-In Data Types- The basic (fundamental) data types
provided by c++ are integral, floating point and void data
type. Among these data types, the integral and floating-
point data types can be preceded by several type
modifiers.
Integral Data Type: The integral data type is used to
store integers and includes char (character) and int
(integer) data types.
Char: Characters refer to the alphabet, numbers and other
characters (such as {, @, #, etc.) defined in the ASCII
character set. In C++, the char data type is also treated as
an integer data type as the characters are internally stored
as integers that range in value from -128 to 127.
Int: Numbers without the fractional part represent integer
data. In C++, the int data type is used to store integers
such as 4, 42, 5233, -32, -745.
DATATYPES IN C++
Floating-point Data Type: A floating-point data type is
used to store real numbers such as 3 .28, 64. 755765, 8.01,
-24.53. This data type includes float and double' data types.
Void: The void data type is used for specifying an empty
parameter list to a function and return type for a function.
When void is used to specify an empty parameter list, it
indicates that a function does not take any arguments and
when it is used as a return type for a function, it indicates
that a function does not return any value. For void, no
memory is allocated and hence, It cannot store anything.
Bool Data type: The bool data type can hold only Boolean
values, that is; either true or false, where true represents 1
and false represents O. It requires only one bit of storage,
however, it is stored as an integer in the memory. Thus, it is
also considered as an integral data type.
DATATYPES IN C++
 Derived Data Types- Data types that are derived from the built-in
data types are known as derived data types. The various derived
data types provided by C++ are arrays, junctions, references and
pointers.
 Array An array is a set of elements of the same data type that are
referred to by the same name. All the elements in an array are
stored at contiguous (one after another) memory locations and each
element is accessed by a unique index or subscript value.
 Function A function is a self-contained program segment that
carries out a specific well-defined task.
 Reference A reference is an alternative name for a variable. That
is, a reference is an alias for a variable in a program. A variable and
its reference can be used interchangeably in a program as both
refer to the same memory location.
 Pointer A pointer is a variable that can store the memory address
of another variable. Pointers allow to use the memory dynamically.
That is, with the help of pointers, memory can be allocated or de-
allocated to the variables at run-time, thus, making a program more
efficient.
DATATYPES IN C++
User-Defined Data Types- Various user-defined data
types provided by C++ are structures, unions,
enumerations and classes.
Structure, Union and Class: Structure and union are
the significant features of C language. Structure and
union provide a way to group similar or dissimilar data
types referred to by a single name. However, C++ has
extended the concept of structure and union by
incorporating some new features in these data types to
support object -oriented programming.
C++ offers a new user-defined data type known as class,
which forms the basis of object-oriented programming. A
class acts as a template which defines the data and
functions that are included in an object of a class. Classes
are declared using the keyword class. Once a class has
been declared, its object can be easily created.
REFERNCE VARIABLES
OPERATORS IN C++
C++ has a rich set of operators. All C operators
are valid in C++ also. C++ introduces some
new operators such as:
Input Operator
Output Operator
Scope Resolution Operator
Memory Management Operators
Manipulators
Comma Operator
Type Cast Operator
OPERATORS IN C++
 Scope Resolution Operator- In C++ program we can use the same variable
names but in separate blocks. The declaration of same variable names refers
to different memory locations. When we declare a variable it is available only
to a specific block of the program. The remaining block cannot access the
variable.
 The scope resolution operator :: allows a programmer to access a global
variable name even if it is hidden by a local re-declaration of that name. The
syntax of scope resolution operator is:
 :: variable_name
 Example:
 #include <iostream.h>
 #include <conio.h>
 int a= 10;
 void main()
 {
 clrscr();
 int a=20;
 cout<<”::a=”<<::a;
 cout<<”a=”<<a;
 getch();
 }
OPERATORS IN C++
 Memory Management Operator
 There are two types of memory management operators in C++:
 new
 delete
 new operator- The new operator in C++ is used for dynamic
storage allocation. This operator can be used to create object of
any type. The general syntax of new operator in C++ is as follows:
 pointer variable = new datatype;
 For example:
 int *a=new int;
 In the above example, the new operator allocates sufficient
memory to hold the object of datatype int and returns a pointer to
its starting point. The pointer variable a holds the address of
memory space allocated.
 The assignment can be made in either of the two ways:
 int *a = new int;*a = 20; or
 int *a = new int(20);
OPERATORS IN C++
delete operator: The delete operator in C++ is used for
releasing memory space when the object is no longer
needed. Once a new operator is used, it is efficient to use
the corresponding delete operator for release of memory.
The general syntax of delete operator in C++ is as
follows:
delete pointer variable;
OPERATORS IN C++
Example:
#include <iostream>
#include<conio.h>
void main()
{
int *a= new int;
*a=100;
cout << " The Output is:a= " << *a;
delete a;
getch();
}
MANIPULATORS

endl manipulator

setw manipulator
MANIPULATORS
TYPECAST OPERATOR
CONTROL STRUCTURES
FUNCTIONS IN C++
 Functions are used to provide modularity to a program. Creating
an application using function makes it easier to understand, edit,
check errors etc.
 Syntax of Function
 return-type function-name (parameters)
{
 // function-body
}
 return-type: suggests what the function will return. It can be int,
char, some pointer or even a class object. There can be functions
which does not return anything, they are mentioned with void.
 Function Name: is the name of the function, using the function
name it is called.
 Parameters: are variables to hold values of arguments passed
while function is called. A function may or may not contain
parameter list.
 Function body: is he part where the code statements are written.
FUNCTIONS IN C++
 void sum(int x, int y)
{
 int z;
 z = x + y;
 cout << z;
}
 int main()
{
 int a = 10;
 int b = 20;
 sum (a, b);
}
 Here, a and b are sent as arguments, and x and y are
parameters which will hold values of a and b to perform
required operation inside function.
FUNCTIONS IN C++
 Declaring, Defining and Calling Function
 Function declaration, is done to tell the compiler about the existence of the
function. Function's return type, its name & parameter list is mentioned.
Function body is written in its definition.
 #include < iostream>
 #include<conio.h>
 int sum (int x, int y); //declaring function
 void main()
 {
 int a = 10;
 int b = 20;
 int c = sum (a, b); //calling function
 cout << c;
 getch();
 }
 int sum (int x, int y) //defining function
 {
 return (x + y);
 }
FUNCTIONS IN C++
 There are many advantages in using functions in a program
they are:
 It makes possible top down modular programming. In this
style of programming, the high level logic of the overall
problem is solved first while the details of each lower level
functions is addressed later.
 The length of the source program can be reduced by using
functions at appropriate places.
 It becomes uncomplicated to locate and separate a faulty
function for further study.
 A function may be used later by many other programs this
means that a c programmer can use function written by
others, instead of starting over from scratch.
 A function can be used to keep away from rewriting the same
block of codes which we are going use two or more locations
in a program. This is especially useful if the code involved is
long or complicated
FUNCTIONS IN C++
A function may belong to any one of the
following categories:
Functions with no arguments and no return
values.
Functions with arguments and no return values.
Functions with arguments and return values.
Functions that return multiple values.
Functions with no arguments and return values.
FUNCTIONS IN C++
Calling a Function
Functions are called by their names. If the
function is without argument, it can be called
directly using its name. But for functions with
arguments, we have two ways to call them,
Call by Value
Call by Reference
Call by Value
In this calling technique we pass the values of
arguments which are stored or copied into the
formal parameters of functions. Hence, the
original values are unchanged only the
parameters inside function changes.
FUNCTIONS IN C++
void calc(int x);
int main()
{
 int x = 10;
 calc(x);
 printf("%d", x);
}
void calc(int x)
{
 x = x + 10 ;
}
Output : 10
FUNCTIONS IN C++
 int calc(int x);
 int main()
{
 int x = 10;
 x = calc(x);
 printf("%d", x);
}
 int calc(int x)
{
 x = x + 10 ;
 return x;
}
 Output : 20
FUNCTIONS IN C++
 Call by Reference
In this we pass the address of the variable as arguments. In this
case the formal parameter can be taken as a reference or a pointer,
in both the case they will change the values of the original variable.
void calc(int &);
int main()
{
int x = 10;
calc(x); // passing address of x as argument
cout<<x;
}

void calc(int &p)


{
p = p + 10;
}
RECURSIVE FUNCTIONS
 A recursive function is one which calls itself.
 Example of finding a factorial in c++
 #include <iostream.h>
 int factorial(int);
 void main(void)
 {
 int number;
 cout << "Please enter a positive integer: ";
 cin >> number;
 if (number < 0)
 cout << "That is not a positive integer.\n";
 else
 cout << number << " factorial is: " << factorial(number) << endl;
 }
 int factorial(int number)
 { int temp;
 if(number <= 1) return 1;
 temp = number * factorial(number - 1);
 return temp;
 }
INLINE FUNCTION
 C++ has a different solution to this problem. To eliminate the
cost of calls to the small functions, C++ proposes a new
feature called as inline function.
 An inline function is a function that is expanded in a line
when it is invoked. That is the compiler replaces the function
call with the corresponding function code.
 An inline function can be defined as follows:-
INLINE FUNCTIONS
Following are the situations where inline function
may not work:-
The function should not be recursive.
Function should not contain static variables.
For functions containing control structure
statements such as switch, if etc.
The function main() cannot work as inline.
The inline functions are similar to macros of C.
The main limitation with macros is that they are
not functions and errors are not checked at the
time of compilation. The function offers better
type testing and do not contain side effects as
present in macros.
INLINE FUNCTIONS
Example: Calculate square using inline and
macros.
 #include<iostream.h>
 #include<conio.h>
 #define SQUARE(v) v * v
 inline float square (float j)
{
 return (j * j);
}
 void main()
{
 clrscr();
 int p = 3, q = 3, r,s;
 r = SQUARE (++p);
 s= square (++q);
 cout<<”r=”<<r<<”\n”<<”s=”<<s;
 getch();
}
 Output
 r=25
INLINE FUNCTIONS
Macros vs Inline functions
Macros are not type safe, and can be expanded
regardless of whether they are syntactically correct -
the compile phase will report errors resulting from
macro expansion problems.
Macros are more flexible, in that they can expand other
macros - whereas inline functions don't necessarily do
this.
Macros can result in side effects because of their
expansion, since the input expressions are copied
wherever they appear in the pattern.
Inline function are not always guaranteed to be inlined
- some compilers only do this in release builds, or when
they are specifically configured to do so. Also, in some
cases inlining may not be possible.
FUNCTION WITH DEFAULT ARGUMENTS
 A default argument is an argument to a function that a
programmer is not required to specify. C++ allows the
programmer to specify default arguments that always have a
value, even if one is not specified when calling the function.
For example, in the following function declaration:
 int my_func(int a, int b, int c=12);
 This function takes three arguments, of which the last one
has a default of twelve. The programmer may call this
function in two ways:
 result = my_func(1, 2, 3);
 result = my_func(1, 2);
 In the first case the value for the argument called c is
specified as normal. In the second case, the argument is
omitted, and the default value of 12 will be used instead.
 There is no means to know if the argument has been
specified by the caller or if the default value was used.
FUNCTION WITH DEFAULT ARGUMENTS
 Example of default arguments in C++
 #include<iostream.h>
 void showVolume(int len, int width, int height=12)
{
 cout<<”Volume =”<<len*width*height;
}
 void main()
{
 showVolume(2,3,4); //takes the height as 4
 showVolume(2,3); // takes the height as default 12
}
 Output:
 Volume=24
 Volume=72
FUNCTION OVERLOADING
Difference between C structure and
C++ structure
C Structure C++ Structure
Structures in C, cannot Structures in C++ can
have member functions hold member functions
inside structures. with member variables.
We cannot initialize the We can directly initialize
structure data directly in structure data in C++.
C.
In C, we have to write In C++, we do not need
‘struct’ keyword to to use ‘struct’ keyword.
declare structure type
variables.
Cannot have static Can have static members.
members.
The data hiding feature is The data hiding feature is
Features/Concepts of Object
Oriented Programming (OOP)
There are some basic concepts that act as
the building blocks of OOPs
Class
Objects
Encapsulation
Abstraction
Polymorphism
Inheritance
Dynamic Binding
Message Passing
Class
Collection of similar types of objects is
called class. It is a logical entity.
A class instance must be created in order to
access and use the user-defined data type's
data members and member functions.
 An class acts as its blueprint for its objects.
 Take the class of cars as an example. Even if
different names and brands may be used for
different cars, all of them will have some
characteristics in common, such as four
wheels, a speed limit, a range of miles, etc.
Object
An Object is an identifiable entity with some
characteristics and behavior. An Object is an
instance of a Class. When a class is defined, no
memory is allocated but when it is instantiated
(i.e. an object is created) memory is allocated.
Encapsulation
Encapsulation is defined as wrapping up data and
information under a single unit. In Object-
Oriented Programming, Encapsulation is defined
as binding together the data and the functions
that manipulate them.
Abstraction
Abstraction means displaying only essential
information and hiding the details. Data
abstraction refers to providing only essential
information about the data to the outside world,
hiding the background details or
implementation.
Polymorphism

Polymorphism means having many forms. In


simple words, we can define polymorphism as
the ability of a message to be displayed in more
than one form.
Inheritance
 The capability of a class to derive properties and
characteristics from another class is called Inheritance.
 Sub class - Subclass or Derived Class refers to a class that
receives properties from another class.
 Super class - The term "Base Class" or "Super Class" refers
to the class from which a subclass inherits its properties.

Dynamic binding
In dynamic binding, the code to be executed in
response to the function call is decided at runtime. C+
+ has virtual functions to support this.
Message Passing
 Objects communicate with one another by sending and
receiving information. A message for an object is a request
for the execution of a procedure and therefore will invoke a
function in the receiving object that generates the desired
results.
CLASSES AND OBJECTS
CLASSES AND OBJECTS
The variables declared inside the class are called as
data members and the functions are known as
member functions. Only the member functions can
have access to private data members and private
functions. However the public members can be
accessed from outside the class.
CREATING OBJECTS OF CLASS
ACCESSING CLASS MEMBERS
THE public KEYWORD
 Public, means all the class members declared under public
will be available to everyone. The data members and
member functions declared public can be accessed by other
classes too. Hence there are chances that they might change
them. So the key members must not be declared public.
 #include<iostream.h>
 #include<conio.h>
 class item
{
 public:
 int codeno;
 float price;
 int qty;
 };

THE public KEYWORD
void main()
{
 clrscr();
 item obj;
 obj.codeno=123;
 obj.price=1000;
 obj.qty=5;
 cout<<”\nCode Number=”<<obj.codeno;
 cout<<”\Price=”<<obj.price;
cout<<”\nQuantity=”<<obj.qty;
getch();
}
THE private KEYWORD
 Private keyword means that no one can access the
class members declared private outside that class. If
someone tries to access the private member, they will
get a compile time error. By default class variables and
member functions are private.
 Example:
 #include<iostream.h>
 #include<conio.h>
 class item
{
 int codeno;
 float price;
 int qty;
 };
THE private KEYWORD
 void main()
{
 clrscr();
 item obj;
 obj.codeno=123;
 obj.price=1000;
 obj.qty=5;
 cout<<”\nCode Number=”<<obj.codeno;
 cout<<”\Price=”<<obj.price;
 cout<<”\nQuantity=”<<obj.qty;
 getch();
}
 As soon as the above code is compiled the compiler will
display error message.
THE protected KEYWORD
Protected, is the last access specifier, and it is
similar to private, it makes class member
inaccessible outside the class. But they can be
accessed by any subclass of that class.
DEFINING MEMBER FUNCTIONS

The member function must be declared inside


the class. They can be defined in
a) private or public section
b) inside or outside the class.
Member Function inside the Class
 The member function defined inside the class are treated as inline function. If the
member function is small then it should be defined inside the class otherwise it
should be defined outside the class.
 #include<iostream.h>
 #include<conio.h>
 class item
 {
 int codeno;
 float price;
 int qty;
 public:
 void show()
 {
 codeno=123;
 price=1000;
 qty=5;
 cout<<”\nCode Number=”<<codeno;
 cout<<”\Price=”<<price;
 cout<<”\nQuantity=”<<qty;
 }
 };
Member Function inside the Class
void main()
{
 clrscr();
 item obj;
 obj.show();
 getch();
}
Output
Code number=123
Price=1000
Quantity=5
Private Member Function
 #include<iostream.h>
 #include<conio.h>
 class item
{
 int codeno;
 float price;
 int qty;

 void values()
 {
 codeno=123;
 price=1000;
 qty=5;
 }
Private Member Function
 public:
 void show()
 {
 values();
 cout<<”\nCode Number=”<<codeno;
 cout<<”\Price=”<<price;
 cout<<”\nQuantity=”<<qty;
 }
 };
 void main()
{
 clrscr();
 item obj;
 obj.values(); // Not Accessible
 obj.show();
 getch();
}
Member Function Outside the Class
 To define a function outside the class following care must be
taken:-
 The prototype of the function must be declared inside the class.
 The function name must be preceded by class name and its
return type separated by scope resolution operator.
 #include<iostream.h>
 #include<conio.h>
 class item
{
 int codeno;
 float price;
 int qty;

 public:
 void show();
 };
Member Function Outside the Class
 void item : : show()
{
 codeno=123;
 price=1000;
 qty=5;
 cout<<”\nCode Number=”<<codeno;
 cout<<”\Price=”<<price;
 cout<<”\nQuantity=”<<qty;
}
 void main()
{
 clrscr();
 item obj;
 obj.show();
 getch();
}
MAKING OUTSIDE FUNCTION INLINE
NESTING OF MEMBER FUNCTION
NESTING OF MEMBER FUNCTION
Data Structure
Data structure is a storage that is
used to store and organize data.
It is a way of arranging data on a
computer so that it can be accessed
and updated efficiently.
It is also used for processing,
retrieving, and storing data. There are
different basic and advanced types of
data structures that are used in almost
every program or software system that
 Linear data structure: Data structure in which data elements
are arranged sequentially or linearly, where each element is
attached to its previous and next adjacent elements, is called a
linear data structure.
Examples of linear data structures are array, stack, queue, linked
list, etc.
Static data structure: Static data structure has a fixed memory
size. It is easier to access the elements in a static data structure.
An example of this data structure is an array.
Dynamic data structure: In dynamic data structure, the size is not
fixed. It can be randomly updated during the runtime which may be
considered efficient concerning the memory (space) complexity of
the code.
Examples of this data structure are queue, stack, etc.
 Non-linear data structure: Data structures where data
elements are not placed sequentially or linearly are called non-
linear data structures. In a non-linear data structure, we can’t
traverse all the elements in a single run only.
Examples of non-linear data structures are trees and graphs.
What is algorithm
An algorithm is a process or a set of rules required
to perform calculations or some other problem-
solving operations especially by a computer.
The formal definition of an algorithm is that it
contains the finite set of instructions which are
being carried in a specific order to perform the
specific task. It is not the complete program or
code; it is just a solution (logic) of a problem, which
can be represented either as an informal description
using a Flowchart or Pseudocode.
Characteristics of an
Algorithm
The following are the characteristics of an
algorithm:
 Input: An algorithm has some input values. We can pass 0 or
some input value to an algorithm.
 Output: We will get 1 or more output at the end of an algorithm.
 Unambiguity: An algorithm should be unambiguous which
means that the instructions in an algorithm should be clear and
simple.
 Finiteness: An algorithm should have finiteness. Here, finiteness
means that the algorithm should contain a limited number of
instructions, i.e., the instructions should be countable.
 Effectiveness: An algorithm should be effective as each
instruction in an algorithm affects the overall process.
 Language independent: An algorithm must be language-
independent so that the instructions in an algorithm can be
implemented in any of the languages with the same output.
Algorithm Complexity
The performance of the algorithm can be measured
in two factors:
 Time complexity: The time complexity of an
algorithm is the amount of time required to
complete the execution. The time complexity of
an algorithm is denoted by the big O notation.
Here, big O notation is the asymptotic notation to
represent the time complexity. The time
complexity is mainly calculated by counting the
number of steps to finish the execution.
 Space complexity: An algorithm's space
complexity is the amount of space required to
solve a problem and produce an output. Similar
Example 1: Write an algorithm to find the maximum of all the
elements present in the array.

Follow the algorithm approach as below:

 Step 1: Start the Program


 Step 2: Declare a variable max with the value of the first element
of the array.
 Step 3: Compare max with other elements using loop.
 Step 4: If max < array element value, change max to new max.
 Step 5: If no element is left, return or print max otherwise goto
step 3.
 Step 6: End of Solution
Complexity of Algorithms

Algorithm complexity measures how many steps are


required by the algorithm to solve the given problem.
It evaluates the order of count of operations executed
by an algorithm as a function of input data size.
O(f) notation represents the complexity of an
algorithm, which is also termed as an Asymptotic
notation or "Big O" notation. Here the f corresponds to
the function whose size is the same as that of the
input data.
Abstract Data type

Abstract Data type (ADT) is a type (or


class) for objects whose behavior is
defined by a set of values and a set of
operations.
The definition of ADT only mentions what
operations are to be performed but not
how these operations will be
implemented. It does not specify how
data will be organized in memory and
what algorithms will be used for
implementing the operations. It is called
Abstract Data type Model
Array
An array is defined as the collection of
similar type of data items stored at
contiguous memory locations.
Arrays are the derived data type in
programming language which can store the
primitive type of data such as int, char,
double, float, etc.
The array is the simplest data structure
where each data element can be randomly
accessed by using its index number.
Initialization of Array
1. The simplest way to initialize an array is by
using the index of each element.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

2. To insert values to it, use a comma-separated list, inside


curly braces:
int myNumbers[] = {25, 50, 75, 100, 70};
Array initialization
(Alternative)
To insert values to it, use a comma-
separated list, inside curly braces:
int myNumbers[] =
{25, 50, 75, 100};
Calculating the address of any
element In the 1-D array:
To find the address of an element in an array the
following formula is used-
Address of A[I] = B + W * (I – LB)
I = Subset of element whose address to
be found,
B = Base address,
W = Storage size of one element store in
any array(in byte),
LB = Lower Limit/Lower Bound of
subscript(If not specified assume zero).
Two Dimensional Array
 The two-dimensional array can be defined as an array of
1- D arrays. The 2D array is organized as matrices which
can be represented as the collection of rows and columns.
 In C, 2-Dimensional arrays can be declared as follows:
Syntax:
Datatype arrayname[size1/row][size2/column];
 Example:

The meaning of the above representation can be


understood as:
The memory allocated to variable b is of data type int.
The data is being represented in the form of 2 rows and 3
columns.
2-D Array representation
2-D Array initialization
Calculating the address of any element
In the 2-D array:
 To find the address of any element in a 2-Dimensional array there are the
following two ways-
 Row Major Order
 Column Major Order
a) Row Major Order
To find the address of the element using row-major order uses the following
formula in A[M][N]:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address, W = Storage size of one element store in an array(in
byte),
LR = Lower Limit of row/start row index of the matrix(If not given assume it as
zero),
LC = Lower Limit of column/start column index of the matrix(If not given
assume it zero)
N = Number of column given in the matrix.
a) Column Major Order
To find the address of the element using row-major order uses the
following formula in
A[M][N]:

Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))

I = Row Subset of an element whose address to be found,


J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LR = Lower Limit of row/start row index of matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of matrix(If not given assume it zero),
M = Number of rows given in the matrix.
 Example: Given an array arr[1………10][1………15] with a
base value of 100 and the size of each element is 1 Byte in
memory find the address of arr[8][6] with the help of column-
major order.

 Formula: used
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
Address of A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1))
= 100 + 1 * ((5) * 10 + (7))
= 100 + 1 * (57)
Address of A[I][J] = 157
Example: A double dimensional array Arr[-10…12, -15…20] contains
elements in such a way that each element occupies 4 byte memory
space. If the base address array is 2000. Find the address of the array
element Arr[-6][8]. Perform the calculations in Row-Major form and
Column-Major form.

Ans: Solution:
 B= 2000
 I= -6
 J= 8
 R0= -10
 C0= -15
 Number of rows (M) = [12-(-10)]+1=23
 Number of columns (N) = [20-(-15)]+1=36
 W=4
Row wise Calculation: Column wise Calculation:
Address of array element Address of array element
Arr[-6][8]= B+ W [N (I – R0) + (J – Arr[-6][8]=
C0)] B+ W [(I – R0) + M (J –
= 2000+4[36(-6-(-10))+(8-(-15))] C0)]
= 2000+4[36(-6+10)+(8+15)] = 2000+4[(-6-(-10))+23(8-(-15))]
= 2000+4*[(36*4)+23] = 2000+4[(-6+10)+23(8+15)]
= 2000+4*[144+23] = 2000+4*[4+(23*23)]
= 2000+4*167 = 2000+4*[4+529]
= 2000+668 = 2000+4*533
= 2668 = 2000+2132
= 4132
An array X [-15……….10, 15……………40]
requires one byte of storage. If beginning
location is 1500 determine the location of X
[15][20] in row major and column major
order.
Row Major: 2285
Column Major: 1660
Array Searching
Linear Search
Binary Search
#include <iostream>
using namespace std; Linear Search in
int main() { C++
int arr[] = {3, 5, 2, 8, 7, 1, 4, 12, 16};
int size = sizeof(arr) / sizeof(arr[0]);
int target, i, result = -1;
cout << "Enter the number you want to search for:
";
cin >> target;
for (i = 0; i < size; ++i)
{ if (arr[i] == target)
{ result = 1;
break;
} }
if (result != -1)
cout << "Element found at position " << i+1 <<
endl;
else
cout << "Element not found in the array" <<
endl;
Binary Search in
#include <iostream>
C++
using namespace std;
int RBS(int arr[], int left, int right, int target)
{
if (left > right)
return -1;
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
return RBS(arr, mid + 1, right, target);
else
return RBS(arr, left, mid - 1, target);
}
int main() {
int arr[] = {12, 17, 25, 31, 49, 55, 78, 84, 90};
int size = sizeof(arr) / sizeof(arr[0]);
int target;
cout << "Enter the number you want to search
for: ";
cin >> target;
int result = RBS(arr, 0, size - 1, target);
if (result != -1) {
cout << "Element found at position " <<
result+1 << endl;
} else {
cout << "Element not found in the array" <<
endl;
}
return 0;
Sorting
Sorting is used to reorder a collection of
items (e.g., numbers, strings) in a
particular order, usually ascending or
descending.
Types:
Bubble sort
Insertion sort
Selection sort
Quick sort
Merge sort
Bubble sort
Bubble sort is a sorting algorithm that
compares two adjacent elements and swaps
them until they are in the intended order.
#include <iostream>
using namespace std;
void bubbleSort(int *arr, int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp; }
} }}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90, 84, 28};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Unsorted array: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
bubbleSort(arr, n);
cout << "\nSorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
Selection Sort
Algorithm
Follow the below steps to solve the problem:
Initialize minimum value(min_idx) to
location 0.
Traverse the array to find the minimum
element in the array.
While traversing if any element smaller
than min_idx is found then swap both the
values.
Then, increment min_idx to point to the
next element.
Repeat until the array is sorted.
#include <stdio.h> int main()
void swap(int *a, int *b) { {
int temp = *a; int i, data[] = {39, 20, 12, 10, 78,
*a = *b; 51, 54, 15, 2};
*b = temp; int size = sizeof(data) /
} sizeof(data[0]);
void selectionSort(int array[], int selectionSort(data, size);
size) cout<<"Sorted array in Acsending
{ int step, i; Order:\n";
for (step = 0; step < size - 1; for (i = 0; i < size; i++)
step++) cout<<data[i]<<" ";
{ int min_idx = step; return 0;
for ( i = step + 1; i < size; i+ }
+)
{
if (array[i] < array[min_idx])
min_idx = i;
}
swap(&array[min_idx],
&array[step]);
}
Insertion Sort
Insertion Sort Algorithm
The simple steps of achieving the insertion sort are listed
as follows -
 Step 1 - If the element is the first element, assume that
it is already sorted. Return 1.
 Step2 - Pick the next element, and store it separately in
a key.
 Step3 - Now, compare the key with all elements in the
sorted array.
 Step 4 - If the element in the sorted array is smaller
than the current element, then move to the next
element. Else, shift greater elements in the array
towards the right.
 Step 5 - Insert the value.
 Step 6 - Repeat until the array is sorted.
int main()
#include <iostream.h> {
void insertionSort(int arr[], int
int i,
n)arr[] = { 102, 98, 13, 51,
{ 75, 66 };
int i, key, j; int n = sizeof(arr) /
for (i = 1; i < n; i++) { sizeof(arr[0]);
key = arr[i];
j = i - 1; insertionSort(arr, n);
while (j >= 0 && arr[j] >cout<<"Sorted
key) array is: \
{ n";
arr[j + 1] = arr[j]; for (i = 0; i < n; i++)
j = j - 1; cout<<arr[i]<<“ ”;
} return 0;
arr[j + 1] = key; }
}
}
Quicksort
 Quicksort is a sorting algorithm based on the
divide and conquer approach where
 An array is divided into subarrays by selecting a
pivot element (element selected from the
array).
 While dividing the array, the pivot element
should be positioned in such a way that
elements less than pivot are kept on the left
side and elements greater than pivot are on the
right side of the pivot.
 The left and right subarrays are also divided
using the same approach. This process
continues until each subarray contains a single
void quickSort(int array[], int low, int
void swap(int *a, int *b) { high) {
int t = *a; if (low < high) {
*a = *b; int pi = partition(array, low, high);
*b = t; quickSort(array, low, pi - 1);
} quickSort(array, pi + 1, high);
// function to find the partition }
position }
void printArray(int array[], int size) {
int partition(int array[], int low, int
for (int i = 0; i < size; ++i) {
high)
cout<<array[i];
{ }
int pivot = array[high]; cout<<endl;
int i = (low - 1); }
for (int j = low; j < high; j++) {int main() {
if (array[j] <= pivot) { int data[] = {68, 7, 2, 41, 90, 9, 6,
i++; 23, 11, 21};
swap(&array[i], &array[j]); int n = sizeof(data) / sizeof(data[0]);
} cout<<"Unsorted Array\n";
printArray(data, n);
}
quickSort(data, 0, n - 1);
swap(&array[i + 1], cout<<"Sorted array in ascending
&array[high]); order: \n";
Merge Sort
Merge sort is defined as a sorting algorithm
that works by dividing an array into smaller
subarrays, sorting each subarray, and then
merging the sorted subarrays back together
to form the final sorted array.
Algorithm
#include <stdlib.h>
void merge(int arr[], int l, int m, int r) /* Copy the remaining elements of L[], if there
{ are any */
int i, j, k; while (i < n1) {
int n1 = m - l + 1; arr[k] = L[i];
int n2 = r - m; i++;
int L[n1], R[n2]; k++;
}
for (i = 0; i < n1; i++)
L[i] = arr[l + i]; while (j < n2) {
for (j = 0; j < n2; j++) arr[k] = R[j];
R[j] = arr[m + 1 + j]; j++;
k++;
i = 0; // Initial index of first subarray }
j = 0; // Initial index of second subarray }
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++; }
void mergeSort(int arr[], int l, int
int main()
r) {
{ int arr[] = { 10, 13, 5, 76, 17, 33, 22, 54,
if (l < r) { 9, 43, 27 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
int m = l + (r - l) / 2;
cout<<"Given array is \n";
mergeSort(arr, l, m); printArray(arr, arr_size);
mergeSort(arr, m + 1, r); mergeSort(arr, 0, arr_size - 1);
merge(arr, l, m, r); cout<<"\nSorted array is \n";
} printArray(arr, arr_size);
} return 0;
}
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
cout<< A[i];
cout<<"\n";
}
Comparative analysis of searching
and sorting algorithms

You might also like