DS Unit 1
DS Unit 1
DS Unit 1
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;
}
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
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