Introduction To Data Structures & Algorithms
Introduction To Data Structures & Algorithms
Data Structures
What The Course Is About
Data structures is concerned with the
representation and manipulation of
data.
All programs manipulate data.
Data manipulation requires an
algorithm.
What The Course Is About
• Algorithm design methods are needed
to develop programs that do the data
manipulation.
• The study of data structures and
algorithms is fundamental to Computer
Science.
Sorting
Rearrange a[0], a[1], …, a[n-1] into
ascending order. When done, a[0] <=
a[1] <= … <= a[n-1]
8, 6, 9, 4, 3 => 3, 4, 6, 8, 9
Sort Methods
Insertion Sort
Bubble Sort
Selection Sort
Count Sort
Shaker Sort
Shell Sort
Heap Sort
Merge Sort
Quick Sort
Insert An Element
Given a sorted list/sequence, insert a
new element
Given 3, 6, 9, 14
Insert 5
Result 3, 5, 6, 9, 14
Insert an Element
3, 6, 9, 14 insert 5
Compare new element (5) and last one
(14)
Shift 14 right to get 3, 6, 9, , 14
Shift 9 right to get 3, 6, , 9, 14
Shift 6 right to get 3, , 6, 9, 14
Insert 5 to get 3, 5, 6, 9, 14
Insert An Element
// insert t into a[0:i-1]
int j;
for (j = i - 1; j >= 0 && t < a[j]; j--)
a[j + 1] = a[j];
a[j + 1] = t;
Insertion Sort
Start
with a sequence of size 1
Repeatedly insert remaining elements
Insertion Sort
Sort 7, 3, 5, 6, 1
Start with 7 and insert 3 => 3, 7
Insert 5 => 3, 5, 7
Insert 6 => 3, 5, 6, 7
Insert 1 => 1, 3, 5, 6, 7
Insertion Sort
for (int i = 1; i < a.length; i++)
{// insert a[i] into a[0:i-1]
// code to insert comes here
}
Insertion Sort
for (int i = 1; i < a.length; i++)
{// insert a[i] into a[0:i-1]
int t = a[i];
int j;
for (j = i - 1; j >= 0 && t < a[j]; j--)
a[j + 1] = a[j];
a[j + 1] = t;
}
ALGORITHMS
Definition
What is an Algorithm?
Informally an algorithm is any well-defined
computational procedure that takes some value
or set of values as input and produces some
value or set of values as output.
An algorithm is thus a sequence of
computational steps that transform the input
into the output.
You can also view an algorithm as a tool for
solving a well-specified computational problem.
Definition
An algorithm is a set of well-defined
steps required to accomplish some
task.
Algorithms also usually involve taking a
system from one state to another,
possibly transitioning through a series
of intermediate states along the way.
Algorithms
Look at the problem : we need to sort a sequence
of numbers into non deceasing order.