64
Data Structure and Algorithm Analysis Slide Set 2 13 CS- I & II Engr. Maria Shaikh [email protected]

DATA STRUCTURES AND ALGORITHM PART 2

  • Upload
    maya

  • View
    8

  • Download
    2

Embed Size (px)

DESCRIPTION

DATA STRUCTURES AND ALGORITHM PART 2

Citation preview

  • Data Structure and Algorithm Analysis

    Slide Set 2

    13 CS- I & II

    Engr. Maria Shaikh

    [email protected]

  • 9/9/2014 2

    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

    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 3

  • 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 4

  • ONE DIMENSIONAL ARRAY

    9/9/2014 Engr. Maria Shaikh 5

  • 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 individuallycould be easily accessed with the use of loop.

    For loop is better to use, as array size is fixed and almostknown 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 (1less than arrays size). To access elements inside age array ofsize 4, we will use following loop.

    for (int i=0;i

  • 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 9

  • Multi Dimensional Array

    9/9/2014 Engr. Maria Shaikh 10

  • 714

    32

    58

    0

    5

    8

    16

    9

    23

    a[0] i=0

    a[1] i=1

    a[2] i=2

    a[3] i=3

    a[4] i=4

    a[5] i=5

    a[6] i=6

    a[7] i=7

    a[8] i=8

    a[9] i=9

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

    Integer array a.

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

    Take positing variable i.

    Its storage will be continuous 20 bytes(2 bytes each).

    Creation of Integer Array

  • 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 wewant to count the number of elements of A, this can be accomplished bytraversing A, that is, by accessing and processing each element of a exactlyones.

    The following algorithm traverses a linear array LA. The simplicity of thealgorithm comes from the fact that LA is a linear structure. Other linearstructures, such as linked list, can also be easily traversed. On the other hand,traversal of nonlinear structures, such as trees and graph, is considerablymore 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

  • 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

    using namespace std;

    int main()

    {

    int n=5,Data[6];

    for(int a =0;a

  • C++ Implementation of Traversing Algorithm

    }

    cout

  • 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= 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

    using namespace std;

    int main()

    {

    cout

  • C++ Implementation of Insertion Algorithm

    cout

  • C++ Implementation of Insertion Algorithm

    a[pos]=item;

    n=n+1;

    cout

  • 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

  • C++ Implementation of Deletion Algorithm

    #include

    using namespace std;

    int main()

    {

    int Array[10];

    int ITEM,K,N=10;

    for (int i=0;i

  • C++ Implementation of Deletion Algorithm

    cout

  • C++ Implementation of Deletion Algorithm

    if(i

  • 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 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 controlledby the variable PTR, and the loop is contained in anouter loop which is controlled by an index K. Alsoobserve that PTR is used as a subscript but K is notused as a subscript, but rather as a counter.

    9/9/2014 Engr. Maria Shaikh 37

  • C++ Implementation of Bubble Sort Algorithm

    #include

    using namespace std;

    int main()

    {

    int i,j, n;

    coutn;

    int a[n];

    for(int x=1; x

  • C++ Implementation of Bubble Sort Algorithm

    }

    for(int i=1; i

  • C++ Implementation of Bubble Sort Algorithm

    for(int x=1; x

  • 9/9/2014 41

  • 42

    Searching

    The goal of the search is to find all records with keys matchinga given search key.

    Applications of searching are widespread, and involve a varietyof different operations.

    Two common terms often used to describe data structures forsearching are dictionaries and symbol tables.

    In searching have programs that are in widespread and frequentuse to study a variety of methods that store records in arraysthat are either searched with key comparisons or indexed bykey value.

  • 43

    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.

  • 44

    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

  • Searching

    9/9/2014 Engr. Maria Shaikh 45

    Algorithm.

  • Linear Search

    9/9/2014 Engr. Maria Shaikh 46

  • Algorithm- Linear Search

    9/9/2014 Engr. Maria Shaikh 47

    (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

  • C++ Implementation of Linear Search Algorithm

    #include

    using namespace std;

    int main() {

    coutsize;

    int array[size], key,i;

    // Taking Input In Array

    for(int j=0;j

  • C++ Implementation of Linear Search Algorithm

    cout

  • C++ Implementation of Linear Search Algorithm

    if(key==array[i]){

    cout

  • 9/9/2014 Engr. Maria Shaikh 51

  • Binary Search

    Suppose DATA is an array which is sorted in increasing numerical order orequivalently alphabetically then there is an extremely efficient searchingalgorithm called binary search which can be used to find the location of agiven 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. Duringeach stage of our algorithm, our search ITEM is reduced to a segment ofelement 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 ITEMis given item of information. The variables BEG, END and MID denote,respectively, the beginning end and middle location of the segment of anelement of DATA. This algorithm finds the location LOC of ITEM in DATA orset 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

  • 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

    using namespace std;

    int main()

    {

    int size, loc;

    int beg=1,end=size;

    int mid=int(beg+end)/2;

    coutsize;

    int array[size], key,i;

    // Taking Input In Array

    for(int j=1;j

  • C++ Implementation of Binary Search Algorithm

    cin>>array[j];

    }

    //Your Entered Array Is

    for(int a=1;a

  • C++ Implementation of Binary Search Algorithm

    array[i]=array[x];

    array[x]=temp;

    }

    }

    cout

  • C++ Implementation of Binary Search Algorithm

    if(key

  • C++ Implementation of Binary Search Algorithm

    }

    else

    {

    cout

  • 9/9/2014 Engr. Maria Shaikh 63

  • FOR POINTERS ARRAY REFER YOUR

    CLASS WORK

    9/9/2014 Engr. Maria Shaikh 64