Вы находитесь на странице: 1из 64

Data Structure and Algorithm

Analysis
Slide Set 2
13 CS- I & II
Engr. Maria Shaikh
maria.sheikh@faculty.muet.edu.pk

Arrays
An array is a fixed number of data items that are stored contiguously and
that are accessible by an index
An Array is a linear collection of Homogeneous data items.
An array is a collection of elements of similar data type.
Contiguous memory allocation takes place.
An array is a DS in which we can access every element directly using position
variable .
It is rather an organizational concept.
Array elements can be accessed individually

9/9/2014

Engr. Maria Shaikh

Types of array
ONE DIMENSIONAL ARRAY:
One-dimensional array (or linear array) is a set of n finite numbers of
homogenous data elements such as
1. The elements of the array are referenced respectively by an index set
consisting of n consecutive numbers.
2. The elements of the array are stored respectively in successive memory
locations.
n number of elements is called the length or size of an array. The elements of
an array A may be denoted in C as
A[0], A[1], A[2], ...... A[n1].
The number n in A[n] is called a subscript or an index and A[n] is called a
subscripted variable. :
9/9/2014

Engr. Maria Shaikh

ONE DIMENSIONAL ARRAY


The length or the number of data elements of the
array can be obtained from the index set by the
formula
Length = UB LB + 1
If n is 10, then the array elements A[0], A[1]......A[9]
are stored in sequential memory locations as follows

9/9/2014

Engr. Maria Shaikh

ONE DIMENSIONAL ARRAY

9/9/2014

Engr. Maria Shaikh

Syntax for single dimensional Array

Now this age array will have four elements, starting from age[0] ..
To age [3], total 4 elements. So, the index of first element is zero and
last element is one less than arrays size i.e. 3 = 4-1.

Engr. Maria Shaikh

Arrays inside the memory


Arrays elements inside the memory
are placed sequentially.
The figure shows typical elements
placed inside the array named age[ ].
Now all elements are of integer data
type.

Engr. Maria Shaikh

Accessing array elements


As Array Elements are sequential in nature, they individually
could be easily accessed with the use of loop.
For loop is better to use, as array size is fixed and almost
known in all cases.
So, we can access each element of an array using a for loop,
starting its counter variable from 0, to the last element (1
less than arrays size). To access elements inside age array of
size 4, we will use following loop.
for (int i=0;i<4; i++) or for (int i=0; i<=3; i++)
Engr. Maria Shaikh

Multi Dimensional Array


If we are reading or writing two-dimensional array,
two loops are required.
Similarly the array of n dimensions would require n
loops. The structure of the two dimensional array is
illustrated in the following figure :
int A[10][10];

9/9/2014

Engr. Maria Shaikh

Multi Dimensional Array

9/9/2014

Engr. Maria Shaikh

10

Creation of Integer Array


7

a[0] i=0

int a[10]={7,1,32,58,0,5,8,16,9,23};

14

a[1] i=1

Integer array a.

32

a[2] i=2

It is of dimension 10 (from 0 to 9).

58

a[3] i=3

a[4] i=4

Take positing variable i.

a[5] i=5

a[6] i=6

Its storage will be continuous 20 bytes(2


bytes each).

16

a[7] i=7

23

a[8] i=8
a[9] i=9

Basic Operations of an Array


Traversing Linear Array:
Let A be a collection of data elements stored in the memory of the computer.
Suppose we want to print the content of each element of A or suppose we
want to count the number of elements of A, this can be accomplished by
traversing A, that is, by accessing and processing each element of a exactly
ones.
The following algorithm traverses a linear array LA. The simplicity of the
algorithm comes from the fact that LA is a linear structure. Other linear
structures, such as linked list, can also be easily traversed. On the other hand,
traversal of nonlinear structures, such as trees and graph, is considerably
more complicated.
9/9/2014

Engr. Maria Shaikh

12

Algorithm: (Traversing a Linear Array)


Here LA is a linear array with lower bound LB and upper bound UB. This
algorithm traverses LA applying an operation PROCESS to each element of LA.

1. [Initialize counter] Set k: =LB.


2. Repeat steps 3 and 4 while k <=UB.
3. [Visit Element] Apply PROCESS to LA [k].
4. [Increase Counter] Set k: =k + 1.
[End of step 2 loop]
5. Exit.
The operation PROCESS in the traversal algorithm may use certain variables which must be
initialized before PROCESS is applied to any of the elements in the array. Accordingly, the
algorithm may need to be proceeded by such an initialization step..
9/9/2014

Engr. Maria Shaikh

13

Algorithm II: (Traversing a Linear Array)


We also state an alternative form of the algorithm which uses a
repeat-for loop instead of the repeat-while loop.
Here LA is a linear array with lower bound LB and upper bound UB.
This algorithm traverses LA applying an operation PROCESS to
each element of LA.
1. Repeat for k = LB to UB:
Apply PROCESS to LA [k].
[End of loop]
2. Exit.
9/9/2014

Engr. Maria Shaikh

14

C++ Implementation of Traversing Algorithm


#include<iostream>
using namespace std;
int main()
{
int n=5,Data[6];
for(int a =0;a<=n;a++)
{
cout<<"Data ["<<a<<"] =";
cin>>Data[a];
cout<<endl;
9/9/2014

Engr. Maria Shaikh

15

C++ Implementation of Traversing Algorithm


}
cout<<"Array is:"<<" ";
cout<<"Data ["<<n<<"] = {";
for ( int k=0;k<=n;k++)
{
if (k<n)
cout<<Data[k]<<',';
else
cout<<Data[k]<<'}';
}
return 0;
}
9/9/2014

Engr. Maria Shaikh

16

9/9/2014

Engr. Maria Shaikh

17

Algorithm for Insertion


(Inserting into Linear Array) INSERT (LA, N, K, ITEM)
Here LA is a linear array with N elements and K is a positive integer such that
K<=N. The algorithm inserts an element ITEM into the Kth position in LA.
1. [Initialize counter] Set J: = N.
2. Repeat Steps 3 and 4 while j >= k;
3. [Move jth element downward.] Set LA [J + 1]: =LA [J].
4. [Decrease counter] Set J: = J-1
[End of step 2 loop]
5. [Insert element] Set LA [K]:=ITEM.
6. [Reset N] Set N:=N+1
7. EXIT.
9/9/2014

Engr. Maria Shaikh

18

C++ Implementation of Insertion Algorithm


#include<iostream>
using namespace std;
int main()
{
cout<<endl;
int a[60],n,item,pos;
cout<<"enter the no of element to array:"<<" ";
cin>>n;
cout<<"enter the elements"<<" ";
for(int r=0;r<=n;r++)
{
9/9/2014
Engr. Maria Shaikh

19

C++ Implementation of Insertion Algorithm


cout<<"A["<<r<<"]="<<" ";
cin>>a[r];
}
cout<<"enter the item to be inserted:"<<" ";
cin>>item;
cout<<"enter the position you want to insert:"<<" ";
cin>>pos;
for(int b=n;b>=pos;b--)
{
a[b+1]=a[b];
}
9/9/2014

Engr. Maria Shaikh

20

C++ Implementation of Insertion Algorithm


a[pos]=item;
n=n+1;
cout<<"the modified array is \n";
cout<<"A["<<n<<"]="<<'{';
for(int j=0;j<=n;j++)
{

if(j<n)
cout<<a[j]<<',';
else
cout<<a[j]<<'}';
}
return 0;
}
9/9/2014

Engr. Maria Shaikh

21

9/9/2014

Engr. Maria Shaikh

22

Algorithm for Deletion


The following algorithm deletes the Kth element from a linear array LA and
assigns it to a variable ITEM.

(Deletion from a Linear Array) DELETE (LA, N, K, ITEM)


Here LA is a Linear Array with N elements and K is the positive integer such
that K<=N. This algorithm deletes the Kth element from LA.
1. Set ITEM: = LA [k].
2. Repeat for J = K to N 1.
[Move J + 1st element upward] Set LA [J]: = LA [J +1].
[End of loop]
3. [Reset the number N of elements in LA] Set N: = N-1
4. EXIT
9/9/2014

Engr. Maria Shaikh

23

C++ Implementation of Deletion Algorithm


#include<iostream>
using namespace std;
int main()
{
int Array[10];
int ITEM,K,N=10;
for (int i=0;i<N;i++)
{
cout<<"ARRAY ["<<i<<"] = ";
cin>>Array[i];
cout<<endl;
}
9/9/2014

Engr. Maria Shaikh

24

C++ Implementation of Deletion Algorithm


cout<<"enter the position you want to delete the item:"<<" ";
cin>>K;
for(int j=(K-1);j<=(N-1);j++)
{
Array[j]=Array[j+1];
}
N=N-1;
cout<<"the modified array is \n";
cout<<"Araay["<<N<<"] ="<<'{';
for(int i=0; i<N;i++)
{

9/9/2014

Engr. Maria Shaikh

25

C++ Implementation of Deletion Algorithm


if(i<N)
cout<<Array[i]<<',';
else
cout<< Array[i]<<" "<<'}';

}
return 0;
}
9/9/2014

Engr. Maria Shaikh

26

9/9/2014

Engr. Maria Shaikh

27

Sorting- Bubble Sort


There are many sorting algorithms. This section describes the
sorting algorithm, called bubble sort, to sort a list.
Suppose list[0]......list[n-1]is a list of n elements, indexed 0 to n-1.
We want to rearrange, that is, sort, the elements of list in
increasing order. The bubble sort algorithm works as follows:
In a series of n-1 iterations, the successive elements list [index]
and list[index+1] of List are compared. If list [index] is greater
than list [index+1], then the elements list[index] and list[index+1]
are swapped, that is, interchanged.

9/9/2014

Engr. Maria Shaikh

28

Sorting- Bubble Sort


It follows that the smaller elements move toward the top (beginning), and the
larger elements move toward the bottom (end) of the list.
In the first iteration, we consider list[0]...list[n-1]; in the second iteration, we
consider list[0]...list[n - 2]; in the third iteration, we consider list[0]...list[n-3],
and so on. For example, consider list[0]............list[4], as shown in Figure

9/9/2014

Engr. Maria Shaikh

29

9/9/2014

Engr. Maria Shaikh

30

9/9/2014

Engr. Maria Shaikh

31

9/9/2014

Engr. Maria Shaikh

32

9/9/2014

Engr. Maria Shaikh

33

Sorting- Bubble Sort


Suppose the list of numbers A [1], A [2], A [3], , A[n] is in
memory. The bubble sort algorithm works as
Step 1: Compare A [1] and A[2] and arrange them in the desired
order, so that A [1] < A [2]. Then compare A [2] and A [3] and
arrange them so that A [2] < A [3]. Then Compare A [3] and A [4]
and arrange them so that A [3] < A [3]. Continue until we compare
A [n-1] with A [n] and arrange them so that A [n-1] < A [n].
Observe that step 1 involves n-1 comparisons. When step 1 is
completed, A[n] will contain the largest element.
9/9/2014

Engr. Maria Shaikh

34

Sorting- Bubble Sort


Step 2: Repeat Step 1 with one less comparison; that is, now we stop
after we compare and possibly rearrange A [n-2] and A [n-1]. When Step
2 is completed, the second largest element will occupy A [-1].
Step 3: Repeat step 1 with two fewer comparisons; that is, we stop after
we compare and possibly rearrange A [n-3] and A [n-2].

Step n-1: Compare A [1] with A [2] and arrange them so that A [1] < A [2].
After n-1 steps, the list will be sorted in the increasing order.
9/9/2014

Engr. Maria Shaikh

35

Algorithm: (BUBBLE SORT)


Algorithm: (BUBBLE SORT) BUBBLE (DATA, N)
Here DATA is an array with N elements. This algorithm sorts the elements in DATA.
1. Repeat step 2 and 3 for K=1 to N-1
2.
Set PTR :=1 [Initializes pass pointer PTR]
3.
Repeat while PTR <= N-K [Executes pass]
a. If DATA [PTR]> DATA [PTR+1], then:
Interchange DATA [PTR] and DATA [PTR+1].
[End of if structure].
b.
Set PTR: = PTR+1.
[End of inner loop].
[End of Step 1 outer loop].
4. EXIT.
9/9/2014

Engr. Maria Shaikh

36

Algorithm: (BUBBLE SORT)


Observe that there is an inner loop which is controlled
by the variable PTR, and the loop is contained in an
outer loop which is controlled by an index K. Also
observe that PTR is used as a subscript but K is not
used as a subscript, but rather as a counter.

9/9/2014

Engr. Maria Shaikh

37

C++ Implementation of Bubble Sort


Algorithm
#include <iostream>
using namespace std;
int main()
{
int i,j, n;
cout<< "How much number you will sort?" << endl;
cin>>n;
int a[n];
for(int x=1; x<=n;x++)
{
cout<< "Enter "<< " Number " << x <<": " << endl;
cin>>a[x];
9/9/2014

Engr. Maria Shaikh

38

C++ Implementation of Bubble Sort


Algorithm
}
for(int i=1; i<=n;i++)
for(int j=i+1; j<=n;j++)
{
if (a[i]>a[j]){
int temp;
temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
cout<< "Sorted numbers are:" << endl;
9/9/2014

Engr. Maria Shaikh

39

C++ Implementation of Bubble Sort


Algorithm
for(int x=1; x<=n;x++)
{
cout<< a[x] << ", ";
}
return 0;
}

9/9/2014

Engr. Maria Shaikh

40

9/9/2014

41

Searching
The goal of the search is to find all records with keys matching
a given search key.
Applications of searching are widespread, and involve a variety
of different operations.
Two common terms often used to describe data structures for
searching are dictionaries and symbol tables.
In searching have programs that are in widespread and frequent
use to study a variety of methods that store records in arrays
that are either searched with key comparisons or indexed by
key value.
42

Searching (Continue)
Search algorithms as belonging to packages implementing a
variety of generic operations that can be separated from
particular implementations, so that alternate implementations
can be substituted easily. The operations of interest include:

Initialize the data structure.


Search for a record (or records) having a given key.
Insert a new record.
Delete a specified record.
Join two dictionaries to make a large one.
Sort the dictionary; output all the records in sorted order.
43

Searching (Continue)
Search and Insert operation is often included for efficiency in situations where
records with duplicate keys are not to be kept within the data structure
Records with duplicate keys can be handled in several ways:
the primary searching data structure contain only records with distinct
keys
to leave records with equal keys in the primary searching data structure
and return any record with the given key for a search
to assume that each record has a unique identifier (apart from the key)
and require that a search find the record with a given identifier, given the
key
to arrange for the search program to call a specified function for each
record with the given key
44

Searching

Algorithm.

9/9/2014

Engr. Maria Shaikh

45

Linear Search

9/9/2014

Engr. Maria Shaikh

46

Algorithm- Linear Search


(Linear Search) LINEAR (DATA, N, ITEM, LOC)
Here DATA is a linear array with N elements, and ITEM is a given item of information. This
algorithm finds the location LOC of ITEM in DATA, or sets LOC: = 0 if the search is unsuccessful.

1. [Insert ITEM at the end of DATA.] Set DATA [ N+1 ]: = ITEM.


2. [Initialize counter.] Set LOC: = 1.
3. [Search for ITEM.]
Repeat while LOC N and DATA[LOC] ITEM:
Set LOC: = LOC+1.
[End of loop.]
4. [Successful?] If LOC = N+1, then: Set LOC: = 0.
5. Exit
9/9/2014

Engr. Maria Shaikh

47

C++ Implementation of Linear Search


Algorithm
#include<iostream>
using namespace std;
int main() {
cout<<"Enter The Size Of Array: ";
int size;
cin>>size;
int array[size], key,i;
// Taking Input In Array
for(int j=0;j<size;j++){
9/9/2014

Engr. Maria Shaikh

48

C++ Implementation of Linear Search


Algorithm
cout<<"Enter "<<j<<" Element: ";
cin>>array[j];
}
//Your Entered Array Is
for(int a=0;a<size;a++){
cout<<"array[ "<<a<<" ] = ";
cout<<array[a]<<endl;
}
cout<<"Enter Key To Search in Array";
cin>>key;
for(i=0;i<size;i++){
9/9/2014

Engr. Maria Shaikh

49

C++ Implementation of Linear Search


Algorithm
if(key==array[i]){
cout<<"Key Found At Index Number : "<<i<<endl;
break;
}
}
if(i != size){
cout<<"KEY FOUND at index : "<<i;
}
else{
cout<<"KEY NOT FOUND in Array ";
}
return 0;
}
9/9/2014

Engr. Maria Shaikh

50

9/9/2014

Engr. Maria Shaikh

51

Binary Search
Suppose DATA is an array which is sorted in increasing numerical order or
equivalently alphabetically then there is an extremely efficient searching
algorithm called binary search which can be used to find the location of a
given item of information in data array.
The basic idea is that you divide the array being searched into sub-arrays,
and compare the middle element to the value for which you are searching.
The binary search algorithm applied to our DATA works as follows. During
each stage of our algorithm, our search ITEM is reduced to a segment of
element of DATA:
DATA[BEG], DATA[BEG+1], DATA[BEG+2] ,--------------DATA[END]

9/9/2014

Engr. Maria Shaikh

52

Binary Search
Note that the variables BEG and END denote respectively the beginning and
end location of the segments under consideration. The algorithm compares
ITEM with middle element DATA[MID] of the segment, where MID is
obtained by:
MID = INT ( ( BEG + END) / 2 )
a) We use INT (A) for the integer value of A. If DATA [MID] = ITEM then
the search is successful and we set LOC = MID. Otherwise new segment of
DATA obtained as follows:
b) If ITEM < DATA [MID], then ITEM can appear only in the left half of the
segment.
DATA[BEG], DATA[BEG+1] ,--------------DATA [MID -1]
So we reset END: = MID 1 and begin searching again.
9/9/2014

Engr. Maria Shaikh

53

Binary Search
a) If ITEM > DATA [MID], then ITEM can appear only in the right half of
the segment.
DATA [MID+1], DATA[MID+2] ,--------------DATA [END]
So we reset BEG: = MID + 1 and begin searching again.
Initially we begin with the entire DATA; i.e.., we begin with BEG =1 and
END =n, or more generally, with BEG = LB and END = UB.
If ITEM is not in DATA, then eventually we obtain
END < BEG
This condition signals that search is unsuccessful, and in such a case we
assign LOC: = NULL. Here NULL is a value that lies outside the set of
indices of DATA: (In most cases, we can choose NULL=0)
9/9/2014

Engr. Maria Shaikh

54

Binary Search Algorithm


Algorithm: (Binary Search) BINARY (DATA, LB, UB, ITEM, LOC)
Here DATA is stored array with lower bound LU and upper bound UB, and ITEM
is given item of information. The variables BEG, END and MID denote,
respectively, the beginning end and middle location of the segment of an
element of DATA. This algorithm finds the location LOC of ITEM in DATA or
set LOC= NULL.
1. [Initialize segment variable]
Set BEG: = LB, END: = UB and MID: = INT ((BEG+END)/2).
2. Repeat Step 3 and 4 while BEG<= END and DATA [MID]!= ITEM.
3. If ITEM < DATA[MID], then
Set END: = MID-1
9/9/2014

Engr. Maria Shaikh

55

Binary Search Algorithm


ELSE:
Set BEG: = MID+1.
[End of if structure]
4. Set MID: =INT((BIG+END)/2)
[End of Step 2 loop]
5. If DATA[MID]= ITEM then
Set LOC: = MID
ELSE:
Set LOC: = NULL.
[End of if structure]
6. EXIT.
9/9/2014

Engr. Maria Shaikh

56

9/9/2014

Engr. Maria Shaikh

57

C++ Implementation of Binary Search


Algorithm
#include<iostream>
using namespace std;
int main()
{
int size, loc;
int beg=1,end=size;
int mid=int(beg+end)/2;
cout<<"Enter The Size Of Array: ";
cin>>size;
int array[size], key,i;
// Taking Input In Array
for(int j=1;j<=size;j++){
cout<<"Enter "<<j<<" Element: ";
9/9/2014

Engr. Maria Shaikh

58

C++ Implementation of Binary Search


Algorithm
cin>>array[j];
}
//Your Entered Array Is
for(int a=1;a<=size;a++){
cout<<"array[ "<<a<<" ] = ";
cout<<array[a]<<endl;
}
for(int i=1; i<=size;i++)
for(int x=i+1; x<=size; x++)
{
if (array[i]>array[x]){
int temp;
temp = array[i];
9/9/2014

Engr. Maria Shaikh

59

C++ Implementation of Binary Search


Algorithm
array[i]=array[x];
array[x]=temp;
}
}
cout<< "Sorted numbers are:" << endl;
for(int x=1; x<=size;x++)
{
cout<< array[x] << ", ";
}
cout<<"Enter Key To Search in Array";
cin>>key;
while (beg<=end && array[mid]!=key)
{
9/9/2014

Engr. Maria Shaikh

60

C++ Implementation of Binary Search


Algorithm
if(key<array[mid])
end=mid-1;
else
beg=mid+1;
mid=int(beg+end)/2;
}
if (array[mid]==key)
loc=mid;
else
loc=0;
if(loc==0)
{
cout<<"item not found";
9/9/2014

Engr. Maria Shaikh

61

C++ Implementation of Binary Search


Algorithm
}
else
{
cout<<"item is pesent at location:"<<loc;
}
return 0;
}

9/9/2014

Engr. Maria Shaikh

62

9/9/2014

Engr. Maria Shaikh

63

FOR POINTERS ARRAY REFER YOUR


CLASS WORK

9/9/2014

Engr. Maria Shaikh

64

Вам также может понравиться