0% found this document useful (0 votes)
15 views31 pages

DS 2

The document discusses data structures and algorithms. It covers topics like choosing a data structure, abstract data types, arrays, pointers, and operations on arrays. Arrays are described as a fundamental data structure that maps indexes to memory addresses. Common array operations like insertion, deletion, traversal and sorting are explained.

Uploaded by

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

DS 2

The document discusses data structures and algorithms. It covers topics like choosing a data structure, abstract data types, arrays, pointers, and operations on arrays. Arrays are described as a fundamental data structure that maps indexes to memory addresses. Common array operations like insertion, deletion, traversal and sorting are explained.

Uploaded by

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

Data Structures & Algorithms

Ahmad
Lecture 2
Choosing your Data Structure

• While selecting a data structures, these


points must be considered.
1.Analyze the problem to determine the
resource constraints that any solution must
meet
2.Determine the basic operations that must be
supported and quantify the resource
constraints for each operation
3.Select the data structure that best meets
these requirements
Operational Questions

• When selecting data structures, here are


some questions to ask.
– Are all data items inserted into the data
structure at the beginning, or are the
insertions interspersed with other operations?
– Can data items be deleted?
– Are all data items process in some well-
defined order, or is search for specific data
items allowed?
Abstract Data Types and Data Structures
• Type a collection of values

• A simple type has no subparts

• An aggregate type or composite type contains several pieces


of information

• A data item is a piece of information or a record whose value


is drawn from a type.

• It is said to be a member of a type

• A data type is a type together with a collection of operations to


manipulate the type.
Abstract Data Types and Data Structures

• There is a distinction between the logical concept of a


data type and its physical implementation
– Example: Trees can be implemented both in a linked fashion
or an array based fashion

• An Abstract Data Type (ADT) is the realization of a data


type as a software component.

• An ADT does not specify how the data type is


implemented
Abstract Data Types and Data Structures

• A data structure is the implementation for an ADT

• ADT’s allow programmers to manage complexity through


abstraction

• Data items have both a logical and a physical form

• The definition of the data item in terms of an ADT is the


logical form

• The implementation of the data item within the data structure


is its physical form
Arrays
• Two ways of representing linear data structure in
memory.

• Through linear relationship between the elements of by


means of sequential memory locations. Such linear
structures are called Arrays

An array of 5 integers
• Through linear relationship between the elements
represented by means of pointers or links.
Arrays

• In linked list each node contains the data and address of


the next node.

A linked list containing 4 integers


• Arrays are useful when the number of elements to be
stored are is fixed.
• Easy to traverse, search and sort
• Linked lists are used when the number of data items in
the collection are likely to vary. They are hard to
maintain.
Arrays

• An array is a finite collection of similar elements stored in


adjacent memory locations.
• By ‘finite’ we mean that there are specific number of
elements in an array.
• By ‘similar’ we mean that all the elements in array are of
the same type.
– E.g An array may contain all integers or all characters.
So what are Arrays
• Intuitively an array is a set of an index and a value. For
each index there is a value associated with it.
• Arrays are fundamental data structures in that they have
direct correspondence with memory systems on virtually
all computers.
• To retrieve the contents of a word from a memory in a
machine language, we provide an address
• Thus we could think of the entire computer memory as
an array, with the memory addresses corresponding to
array indices.
• In C++ it is the responsibility of programmer to use
indexes that are non negative and smaller than the array
size.
– Neglecting of that responsibility is the one of the common
programming mistakes.
Arrays
• Array
– a set of pairs (index and value)
– Same name and type
• To refer to an element, specify
– Array name
– Position number
• Format:
– arrayname[ position number ]
• Data structure
– For each index, there is a value associated with that index.
• Representation (possible)
– implemented by using consecutive memory.
Types of Arrays

• There are two types of arrays.


– One dimensional arrays
– Multidimensional arrays
• Multidimensional array can be a 2-D array, 3-D array, 4-
D array etc.
• To know that an array is 1-D or 2-D is determined by
array syntax used to declare that array.
Array Operations

• There are several operations that can be performed on


arrays.

Operation Description
Insertion Adding a new element to an array
Deletion Removing an element from an array
Traversal Processing each element in the array
Search Finding the location of an element with a
given value
Sorting Organising the element in some order
Merging Combining two arrays into single array
Reversing Reversing the elements of an array
Array Declaration

• When declaring arrays, specify


– Name
– Type of array
– Number of elements
• arrayType arrayName[ numberOfElements ];
Initializing arrays

• The elements of global and static arrays are automatic


initialised with their default values.
• We have the possibility to assign initial values to each
one of its elements by enclosing the values in braces { }
– int myArray [5] = { 16, 2, 77, 40, 12071 }
Accessing Arrays

• The elements of an array can be accessed individually


as if it is a normal variable. The format is as:
– Name[index]
• For example, to store the value 75 in the third element of
billy, we could write the following statement:
– myArray[2] = 75;
• To pass the value of the third element of billy to a
variable called myVar, we could write:
– myVar=myArray[2];
• In C++ it is syntactically correct to exceed the valid range
of indexes for an array.
– This can create problems, since accessing out-of-range
elements do not cause compilation errors but can cause
runtime errors.
Array Insertion

• There are generally two scenarios for inserting a value


into an array.
– Inserting a value into a specified location of an array.
– Inserting a value into a sorted array
• If a value needs to be inserted into a specified location,
the programmer can simply follow the following steps.
– Insert the value into the position
– Move all other following elements to the next position
– Increment the size of the array.
Array Insertion

• If a value needs to be inserted into a sorted array, the


programmer must first find the location in the array
where the value should be placed in order to keep the
original order in intact.

• Once the target location is found, the steps outlined in


the previous slide can then be executed.
Array Deletion
• Array deletion aimed at removing a certain element at
particular position in that array.

• This operation can be carried out through a deletion


function which deletes the element at the given position

• While doing so it shifts the numbers placed after the


position from where the number is to be deleted, one
place to the left of their existing positions.

• The place that is vacant after deletion of an element is


filled with 0.
Reversing Array

• In the reversing operation the entire array


is reversed by swapping the elements.
Merging of Two Arrays

• Merging of two arrays involve two steps.


– Sorting the arrays to be merged.
– Adding the sorted elements of both the arrays
to a new array in a sorted order.
Pointers
• When we declare a variable some memory is allocated
for it.
• The memory location can be referenced through the
identifier “i”.
• Thus, we have two properties for any variable : its
address and its data value.
• The address of the variable can be accessed through the
referencing operator “&”. “&i” gives the memory location
where the data value for “i” is stored.
• A pointer variable is one that stores an address.
– We can declare pointers as follows int* p; .
• * is the dereference operator
– in a variable definition, this indicates that the variable is a pointer
– & is the address-of operator
• tells us the address of a variable
Pointer Declaration & Derefrencing
• Declaration
int *ip;
double *dp;
float *fp;

• Derefrencing
int *ptr;

• Suppose above pointer stores the address bffe8b3c. Also


suppose that the integer stored at address bffe8b3c has
the value 110.
cout << "The pointer is: " << ptr;
cout << "The target is: " << *ptr;
// Output:
// The pointer is: bffe8b3c
// The target is: 110
Pointers

• Q: Why is it important to declare the type of the


variable that a pointer points to? Aren’t all
addresses of the same length?
Pointer Declaration & Derefrencing
• If you see the * in a declaration statement, with a type in
front of the *, a pointer is being declared for the first time.
• AFTER that, when you see the * on the pointer name, you
are dereferencing the pointer to get to the target.
• Pointers don't always have valid targets.
– A pointer refers to some address in the program's memory space.
– A program's memory space is divided up into segements
– Each memory segment has a different purpose. Some segments
are for data storage, but some segments are for other things, and
off limits for data storage
– If a pointer is pointing into an "out-of-bounds" memory segment,
then it does NOT have a valid target
• If you try to dereference a pointer that doesn't have a valid
target, your program will crash with a segmentation fault
error.
• Don't dereference a pointer until you know it has been
initialized to a valid target!
The null pointer
• There is a special pointer whose value is 0. It is called the null
pointer
ptr = 0;
• The null pointer is the only integer literal that may be assigned to
a pointer. You may NOT assign arbitrary numbers to pointers:
int * p1 = 0; // okay
int * p2; p2 = 0; // okay. null pointer again.
int * p3; p3 = 99; // BAD! cannot assign other literals to pointers!
• The null pointer is never a valid target, however. If you try to
dereference the null pointer, you WILL get a segmentation fault.
• If a pointer's value was completely unknown -- random memory
garbage -- you'd never know if it was safe to dereference
• If you make sure your pointer is ALWAYS set to either a valid
target, or to the null pointer, then you can test for it:
if (ptr != 0) // safe to dereference
cout << *ptr;
Pointers & Arrays
• The concept of array is very similar to the concept of
pointer. The identifier of an array actually a pointer that
holds the address of the first element of the array.
• Therefore if you have two declarations as follows:
int myArr[10]; // myarr is a pointer to first integer in the array
int * p; // p is a pointer. It has the same type as myArr
p = myArr; // legal assignment. Both pointers to int.

myArr[3] = 10;
p[4] = 5;
cout << myArr[6];
cout << p[6];

• The only difference between the two is that we can change


the value of “p” to any integer variable address whereas
“myArr” will always point to the integer array of length 10
defined.
Pointers (to pointers)

• Since pointers are also objects, we can point to them too

int ival = 1024;


int *pi = &ival;
int **ppi = &pi;

• (Is your head exploding yet?)


Recursion
• Recursion is the concept of defining a method that
makes a call to itself

• A method calling itself is making a recursive call

• A method M is recursive if it calls itself (direct recursion)


or another method that ultimately leads to a call back to
M (indirect recursion)
Content of a Recursive Method
• Base case(s)
– Values of the input variables for which we perform no recursive
calls are called base cases (there should be at least one base
case).
– Every possible chain of recursive calls must eventually reach a
base case.

• Recursive calls
– Calls to the current method.
– Each recursive call should be defined so that it makes progress
towards a base case.

You might also like