Data Structures PPT

369
Data Structures & Algorithms Week1

description

Data structure ppt is helpful to know the basic concept.

Transcript of Data Structures PPT

  • Data Structures &AlgorithmsWeek1

  • ContentsTextbookGradeSoftware

  • TextbookC & Data Structures

    P. S. Deshpande, O. G. KakdeCHARLES RIVER MEDIA, INC. Hingham, Massachusetts

  • GradeMidterm test (Lab)Final test (Lab)Project (working on group)Multiple choice testHow to Grade

  • Grade

  • Software: C/C++ edittorBC++, TC++C-Free is a professional C/C++ integrated development environment (IDE) that support multi-compilers. Use of this software, user can edit, build, run and debug programs freely.

    With C/C++ source parser includedLightweight C/C++ development tool. http://www.programarts.com/cfree_en/

  • C/C++ edittor: demoFind max of 3 numbers: a,b,c

    Using scanf, printf (C standard)Using cin, cout (Cpp)

    *#include #include #include

    void main(){int a,b,c;couta>>b>>c;int max=a;if (b>max) max=b;if (c>max) max=c;coutmax) max=c;printf("max= %d",max);}

  • CHAPTER 0: INTRODUTION What is Data Structures?

    A data structure is defined by (1) the logical arrangement of data elements, combined with (2) the set of operations we need to access the elements.

  • Atomic VariablesAtomic variables can only store one value at a time.

    int num;float s;A value stored in an atomic variable cannot be subdivided.

  • What is Data Structures?Example:library

    is composed of elements (books) Accessing a particular book requires knowledge of the arrangement of the books Users access books only through the librarian

    the logical arrangement of data elements, combined withthe set of operations we need to access the elements.

  • Basic Data StructuresStructures include

    linked listsStack, Queuebinary treesand others

  • What is Algorithm?Algorithm:

    A computable set of steps to achieve a desired resultRalationship to Data Structure Example: Find an element

  • Sumary

  • Chapter 0: C LANGUAGE ADDRESSPOINTERSARRAYSADDRESS OF EACH ELEMENT IN AN ARRAYACCESSING & MANIPULATING AN ARRAY USING POINTERSANOTHER CASE OF MANIPULATING AN ARRAY USING POINTERSTWO-DIMENSIONAL ARRAYPOINTER ARRAYSSTRUCTURESSTRUCTURE POINTERS

  • Chapter 0: C LANGUAGE ADDRESSFor every variable there are two attributes: address and value cout
  • Chapter 0: C LANGUAGE 2. POINTERSis a variable whose value is also an address.A pointer to an integer is a variable that can store the address of that integer ia: value of variable&ia: address of ia*ia means you are printing the value at the location specified by ia

  • Chapter 0: C LANGUAGE int i; //A int * ia; //B cout
  • Chapter 0: C LANGUAGE Points to Remember

    Pointers give a facility to access the value of a variable indirectly.You can define a pointer by including a * before the name of the variable.You can get the address where a variable is stored by using &.

  • Chapter 0: C LANGUAGE 3. ARRAYSAn array is a data structure used to process multiple elements with the same data type when a number of such elements are known. An array is a composite data structure; that means it had to be constructed from basic data types such as array integers.

    int a[5]; for(int i = 0;i

  • Chapter 0: C LANGUAGE 4. ADDRESS OF EACH ELEMENT IN AN ARRAYEach element of the array has a memory address. void printdetail(int a[]){ for(int i = 0;i
  • Chapter 0: C LANGUAGE 5. ACCESSING & MANIPULATING AN ARRAY USING POINTERSYou can access an array element by using a pointer. If an array stores integers->use a pointer to integer to access array elements.

  • Chapter 0: C LANGUAGE 6. ANOTHER CASE OF MANIPULATING AN ARRAY USING POINTERSThe array limit is a pointer constant : cannot change its value in the program. int a[5]; int *b; a=b; //errorb=a; //OKIt works correctly even using a++ ???

  • Chapter 0: C LANGUAGE 7. TWO-DIMENSIONAL ARRAYint a[3][2];

  • Chapter 0: C LANGUAGE 8. POINTER ARRAYSYou can define a pointer array (similarly to an array of integers). In the pointer array, the array elements store the pointer that points to integer values.

  • Chapter 0: C LANGUAGE 9. STRUCTURESStructures are used when you want to process data of multiple data types But you still want to refer to the data as a single entity Access data: structurename.membername

  • Chapter 1: C LANGUAGE 10. STRUCTURE POINTERSProcess the structure using a structure pointer

  • CHAPTER 2: FUNCTION & RECURSION 1.FUNCTION2.THE CONCEPT OF STACK3.THE SEQUENCE OF EXECUTION DURING A FUNCTION CALL4.PARAMETER PASSING5.CALL BY REFERENCE6.RESOLVING VARIABLE REFERENCES7.RECURSION8.STACK OVERHEADS IN RECURSION9.WRITING A RECURSIVE FUNCTION10.TYPES OF RECURSION

  • CHAPTER 2: FUNCTION & RECURSION 1.FUNCTION

    provide modularity to the software divide complex tasks into small manageable tasks avoid duplication of work

  • CHAPTER 2: FUNCTION & RECURSION 2.THE CONCEPT OF STACK

    A stack is memory in which values are stored and retrieved in "last in first out" manner by using operations called push and pop.

  • CHAPTER 2: FUNCTION & RECURSION 3.THE SEQUENCE OF EXECUTION DURING A FUNCTION CALL

    When the function is called, the current execution is temporarily stopped and the control goes to the called function. After the call, the execution resumes from the point at which the execution is stopped.To get the exact point at which execution is resumed, the address of the next instruction is stored in the stack. When the function call completes, the address at the top of the stack is taken.

  • CHAPTER 2: FUNCTION & RECURSION 3.THE SEQUENCE OF EXECUTION DURING A FUNCTION CALL

    Functions or sub-programs are implemented using a stack.When a function is called, the address of the next instruction is pushed into the stack.When the function is finished, the address for execution is taken by using the pop operation.

  • CHAPTER 2: FUNCTION & RECURSION 3.THE SEQUENCE OF EXECUTION DURING A FUNCTION CALLResult:?

  • CHAPTER 2: FUNCTION & RECURSION 4.PARAMETER * REFERENCE PASSING

    passing by value the value before and after the call remains the same passing by referencechanged value after the function completes

  • CHAPTER 2: FUNCTION & RECURSION 6.RESOLVING VARIABLE REFERENCES

    When a variable can be resolved by using multiple references, the local definition is given more preference

  • CHAPTER 2: FUNCTION & RECURSION 7.RECURSION

    A method of programming whereby a function directly or indirectly calls itselfProblems: stop recursion?

  • CHAPTER 2: FUNCTION & RECURSION 7.RECURSION

  • CHAPTER 2: FUNCTION & RECURSION 7.RECURSION: Hanoi tower

  • CHAPTER 2: FUNCTION & RECURSION 7.RECURSION

  • CHAPTER 2: FUNCTION & RECURSION 8.STACK OVERHEADS IN RECURSION

    two important results: the depth of recursion and the stack overheads in recursion

  • CHAPTER 2: FUNCTION & RECURSION 9.WRITING A RECURSIVE FUNCTION

    Recursion enables us to write a program in a natural way. The speed of a recursive program is slower because of stack overheads.In a recursive program you have to specify recursive conditions, terminating conditions, and recursive expressions.

  • CHAPTER 2: FUNCTION & RECURSION 10.TYPES OF RECURSION

    LINEAR RECURSION TAIL RECURSIONBINARY RECURSION EXPONENTIAL RECURSION NESTED RECURSIONMUTUAL RECURSION

  • CHAPTER 2: FUNCTION & RECURSION 10.TYPES OF RECURSION

    LINEAR RECURSIONonly makes a single call to itself each time the function runs

  • CHAPTER 2: FUNCTION & RECURSION 10.TYPES OF RECURSION

    TAIL RECURSIONTail recursion is a form of linear recursion. In tail recursion, the recursive call is the last thing the function does. Often, the value of the recursive call is returned.

  • CHAPTER 2: FUNCTION & RECURSION 10.TYPES OF RECURSION

    BINARY RECURSIONSome recursive functions don't just have one call to themself, they have two (or more).

  • CHAPTER 2: FUNCTION & RECURSION 10.TYPES OF RECURSION

    EXPONENTIAL RECURSIONAn exponential recursive function is one that, if you were to draw out a representation of all the function calls, would have an exponential number of calls in relation to the size of the data set (exponential meaning if there were n elements, there would be O(an) function calls where a is a positive number)

  • CHAPTER 2: FUNCTION & RECURSION 10.TYPES OF RECURSION

    EXPONENTIAL RECURSION

  • CHAPTER 2: FUNCTION & RECURSION 10.TYPES OF RECURSION

    NESTED RECURSIONIn nested recursion, one of the arguments to the recursive function is the recursive function itself These functions tend to grow extremely fast.

  • CHAPTER 2: FUNCTION & RECURSION 10.TYPES OF RECURSION

    MUTUAL RECURSIONA recursive function doesn't necessarily need to call itself. Some recursive functions work in pairs or even larger groups. For example, function A calls function B which calls function C which in turn calls function A.

  • CHAPTER 2: FUNCTION & RECURSION 10.TYPES OF RECURSION

    MUTUAL RECURSION

  • Exercises 1: Recursion

  • Exercises 2: RecursionConvert number from H10->H2

  • Week3: Recursion Excercises (1)E1. (44/174) Write a program to compute: S = 1 + 2 + 3 + n using recursion.

  • Week3: Recursion Excercises (2-3)E3(a). Write a program to print a revert number Example: input n=12345. Print out: 54321.

    E3(b). Write a program to print this number Example: input n=12345. Print out: 12345.

  • Week3: Recursion Excercises (4)E4. Write a recursion function to find the sum of every number in a int number. Example: n=1980 => Sum=1+9+8+0=18.

  • Week3: Recursion Excercises (5)E4. Write a recursion function to calculate:

    S=a[0]+a[1]+a[n-1]A: array of integer numbers

  • Week3: Recursion Excercises (6)E4. Write a recursion function to find an element in an array (using linear algorithm)

  • Week3: Recursion Excercises (7)Print triangle

    abcd

  • Week3: Recursion Excercises (8)Convert number from H10->H2

  • Week3: Recursion Excercises (9)Minesweeper

    *#include #include #include void nhap(int a[][5],int m,int n);void xuat(int a[][5],int m,int n);void duyet(int a[][5],int m,int n,int x,int y);int count (int a[][5],int m,int n,int x,int y);//=======================main ===================================

    void main(){//randomize();int a[5][5];nhap (a,5,5);xuat(a,5,5);couty;cout

  • Week 3CHAPTER 3: SEARCHING TECHNIQUES1. LINEAR (SEQUENTIAL) SEARCH2.BINARY SEARCH3. COMPLEXITY OF ALGORITHMS

  • SEARCHING TECHNIQUESTo finding out whether a particular element is present in the list. 2 methods: linear search, binary search The method we use depends on how the elements of the list are organized

    unordered list: linear search: simple, slow an ordered listbinary search or linear search: complex, faster

  • 1. LINEAR (SEQUENTIAL) SEARCHHow?

    Proceeds by sequentially comparing the key with elements in the listContinues until either we find a match or the end of the list is encountered. If we find a match, the search terminates successfully by returning the index of the element If the end of the list is encountered without a match, the search terminates unsuccessfully.

  • 1. LINEAR (SEQUENTIAL) SEARCHvoid lsearch(int list[],int n,int element){ int i, flag = 0; for(i=0;i
  • 1. LINEAR (SEQUENTIAL) SEARCHint lsearch(int list[],int n,int element){ int i, find= -1; for(i=0;i
  • 2.BINARY SEARCHList must be a sorted oneWe compare the element with the element placed approximately in the middle of the listIf a match is found, the search terminates successfully.Otherwise, we continue the search for the key in a similar manner either in the upper half or the lower half.

  • Baba?Eat?

  • void bsearch(int list[],int n,int element){ int l,u,m, flag = 0; l = 0; u = n-1; while(l
  • BINARY SEARCH: Recursionint Search (int list[], int key, int left, int right) { if (left
  • 3. COMPLEXITY OF ALGORITHMSIn Computer Science, it is important to measure the quality of algorithms, especially the specific amount of a certain resource an algorithm needs Resources: time or memory storage (PDA?) Different algorithms do same task with a different set of instructions in less or more time, space or effort than other. The analysis has a strong mathematical background. The most common way of qualifying an algorithm is the Asymptotic Notation, also called Big O.

  • 3. COMPLEXITY OF ALGORITHMSIt is generally written as

    Polynomial time algorithms,

    O(1) --- Constant time --- the time does not change in response to the size of the problem. O(n) --- Linear time --- the time grows linearly with the size (n) of the problem. O(n2) --- Quadratic time --- the time grows quadratically with the size (n) of the problem. In big O notation, all polynomials with the same degree are equivalent, so O(3n2 + 3n + 7) = O(n2) Sub-linear time algorithms

    O(logn) -- Logarithmic time Super-polynomial time algorithms

    O(n!) O(2n)

  • 3. COMPLEXITY OF ALGORITHMSExample1: complexity of an algorithm

    void f ( int a[], int n ){ int i; cout

  • 3. COMPLEXITY OF ALGORITHMSExample2: complexity of an algorithm

    void f ( int a[], int n ){ int i; cout

  • 3. COMPLEXITY OF ALGORITHMSLinear Search

    O(n). Binary Search

    O(log2 N)

  • Week4: (Chapter 4)20 test

    Write a small programInput the number of arrayInput array of integer Display arrayInput a value. Using linear search to find position of first match item in arrayUsing 3 function: enterarray, displayarray,linearfind

  • Week4: (Chapter 4)SORTING TECHNIQUES Why?

    Do binary search Doing certain operations faster

    SORTING

  • Week4: (Chapter 4)SORTING TECHNIQUESGiven a set (container) of n elements

    E.g. array, set of words, etc. Suppose there is an order relation that can be set across the elements Goal Arrange the elements in ascending order

    Start 1 23 2 56 9 8 10 100End 1 2 8 9 10 23 56 100

  • Week4: (Chapter 4)SORTING TECHNIQUESBubble sort, Insertion sort, Selection sort, Quick sort, Heap sort, Merge sort, Exchange sort Focus on

    Bubble sortInsertion sortSelection sortExchange sortQuick sort

  • Week4: (Chapter 4)SORTING TECHNIQUES

    AverageWorstBubble sortExchange sortO(n2)O(n2)Insertion sortO(n2)O(n2)Selection sortO(n2)O(n2)Quick sortO(nlogn)O(n2)

  • 1.Bubble sort: ideaarrange the elements of the list by forming pairs of adjacent elements. The pair of the ith and (i+1)th element. If the order is ascending, we interchange the elements of the pairThis will bring the highest value from among the remaining (n1) values to the (n1)th position.

  • 1.Bubble sort: idea

  • 1.Bubble sort: idea37524compare 3 and 7 ; 7 is > 3 so advance35724compare 7 and 5, 7 > 5 so swap them35274compare 7 and 2, 7 >4 so swap them35247compare 7 and 4, 7 >4 so swap themEnd of pass 1; notice that 7 is in the right placeWhy it is called Bubble?

  • 2.Bubble sort: ideaSimplest sorting algorithmIdea:

    1. Set flag = false2. Traverse the array and compare pairs of two elements 1.1 If E1 E2 - OK1.2 If E1 > E2 then Switch(E1, E2) and set flag = true3. If flag = true goto 1.What happens?

  • 1.Bubble sort:algorithm ideavoid bubbleSort (Array S, length n) {boolean isSorted = false;while(!isSorted) {isSorted = true;for(i = 0; i S[i+1]) {swap(S[i],S[i+1];)isSorted = false;} }

  • 1.Bubble sort: implementvoid bsort(int list[], int n){int count,j;

    for(count=0;count

  • 2. Exchange SortingMethod : make n-1 passes across the data, on each pass compare adjacent items, swapping as necessary (n-1 compares) O(n2)

  • 2. Exchange Sortingvoid Exchange_sort(int arr[], int n){int i,j;

    for(i=0;i

  • 2. Exchange SortingNotes:

    on each successive pass, do one less compare, because the last item from that pass is in placeif you ever make a pass in which no swap occurs, the sort is completeThere are some algorithms to improve performance but Big O will remain O(n2)

  • 3. Insertion SortStrategy: divide the collection into two lists, one listed with one element (sorted) and the other with the remaining elements.On successive passes take an item from the unsorted list and insert it into the sorted list so the the sorted list is always sortedDo this until the unsorted list is empty

  • 3. Insertion Sort37524sortedunsortedtake an item from the unsorted list (7) and insert into the sorted list37524sortedunsortedtake next item from the unsorted list (5) and insert into the sorted list35724sortedunsorted23574sortedunsorted23457sortedunsortedtake next item from the unsorted list (2) and insert into the sorted listtake next item from the unsorted list (4) and insert into the sorted list

  • 3. Insertion Sortvoid insertionSort(int arr[], int n){ int j, key; for(int i = 1; i < n; i++){ key = arr[i]; j = i - 1; while(j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }}

  • 3. Insertion SortNote that each insertion could be O(n-1) and there are n-1 insertions being done therefore Big O is O(n2)This is very much like building an ordered linked list except there is more data movement

  • 4. Selection SortStrategy: make a pass across the data looking for the largest item, swap the largest with the last item in the array. On successive passes (n-1) assume the array is one smaller (the last item is in the correct place) and repeat previous step

  • 4. Selection Sort

    37524biggestlast345273452biggestlast34257342577biggestlast324322357574574

  • 4. Selection Sortvoid selection_sort(int arr[], int n){int i, j, min;for (i = 0; i < n - 1; i++) { min = i; for (j = i+1; j < n; j++) { if (list[j] < list[min]) min = j; } swap(arr[i],arr[min]); }}

  • 4. Selection SortNotice that in selection sort, there is the least possible data movementThere are still n-1 compares on sublists that become one item smaller on each pass so, Big O is still O(n2)This method has the best overall performance of the O(n2) algorithms because of the limited amount of data movement

  • 5. Quick SortThis sorting method by far outshines all of the others for flat out speedBig O is log2nthere are problems, worst case performance is when data is already in sorted order or is almost in sorted order (well analyze this separately) and there are solutions to the problemsand there is an improvement to make it faster still

  • 5. Quick SortSorting algorithms that rely on the DIVIDE AND CONQUER paradigm

    One of the most widely used paradigmsDivide a problem into smaller sub problems, solve the sub problems, and combine the solutionsLearned from real life ways of solving problems

  • 5. Quick SortAnother divide-and-conquer sorting algorihmTo understand quick-sort, lets look at a high-level description of the algorithm

    1) Divide : If the sequence S has 2 or more elements, select an element x from S to be your pivot. Any arbitrary element, like the last, will do. Remove all the elements of S and divide them into 3 sequences:L, holds Ss elements less than xE, holds Ss elements equal to xG, holds Ss elements greater than x2) Recurse: Recursively sort L and G3) Conquer: Finally, to put elements back into S in order, first inserts the elements of L, then those of E, and those of G.

  • 5. Quick Sort: idea1) Select: pick an element

    2) Divide: rearrange elements so that x goes to its final position E

    3) Recurse and Conquer: recursively sort

  • 5. Quick Sort: idea

  • Quick Sort23175121924427826143331134432317512192442782614333113443231751219244278261433311344323175121924427826143331134432317512192442782614333113443Pick the leftmost element as the pivot (23). Now , start two cursors (one at either end) going towards the middle and swap values that are > pivot (found with left cursor) with values < pivot (found with right cursor)swapswapswapswapFinally, swap the pivot and the value where the cursors passed each otherNote : 23 is now in the right place and everything to its left is < 23 and everything to its right is > 23

  • Quick Sort2317512192442782614333113443Now, repeat the process for the right partition17512194814311swap17512194814311swap17512194814311swap17512194814311swapNote: the 11 is now in the right place, and the left partition is all < pivot and the right partition is all > pivot

  • Quick Sort (worst case)If the data is already sorted watch what happens to the partitions

    1751219481431123242726333443There is nothing to swap175121948141123242726333443Again, nothing to swap..The partitions are always the maximum size and the performance degrades to O(n2)

  • Quick Sortvoid quickSort(int Arr[], int lower, int upper){int x = Arr[(lower + upper) / 2];int i = lower; int j = upper;do{ while(Arr[i] < x) i ++; while (Arr[j] > x) j --; if (i
  • Kim tra 15Vit chng trnh han chnhMenu cha 4 chn la

    1. Nhp v kim tra 1 s X c phi l s nguyn t (s X : nhp vo)2. Xut ra cc s nguyn t < n (n nhp vo)3. Xut ra n s nguyn t u tin (n nhp vo)4. That chng trnhS dng hm hp l.Ch : li syntax

  • Common logic errorEnding loop with ;

    int sum = 0;for (i=1;i

  • Common logic errorint i, flag = 0;for(i=0;i
  • Week 5: STACKS AND QUEUES STACKS: concept QUEUES : conceptSTACKS,QUEUES : implement

    Using arrayUsing Linked List (next chapter)

  • 1.StackLIFO (last in first out)

  • 1.StackManaging Top element

  • 1.Stack: implement using array#define MAX 10 void main(){ int stack[MAX]; int top = -1; push(stack,top, 10 ); pop(stack,top,value); int value;

    cout

  • 1.Stack: implement using arrayvoid push(int stack[], int &top, int value){ if(top < MAX ) { top = top + 1; stack[top] = value; } else cout
  • 1.Stack: implement using arrayvoid pop(int stack[], int &top, int &value){ if(top >= 0 ) { value = stack[top]; top = top - 1; }else cout
  • 2.QUEUEFIFO (first in first out)

  • 2.QUEUE: implement using array

    A circular queue

  • 2.QUEUE: implement using array#define MAX 10void main(){ int queue[MAX]; int bottom,top,count=0; bottom=top=-1;

    enqueue(queue,count,top, 100 ); int value; dequeue(queue,count,bottom,top,value);

    }

  • 2.QUEUE: implement using arrayvoid enqueue(int queue[],int &count, int &top, int value){ if(count< MAX) { count++; top= (top +1)%MAX; queue[top] = value; } else cout
  • 2.QUEUE: implement using arrayvoid dequeue(int queue[], int &count,int &bottom,int top, int &value){ if(count==0) { cout
  • 3. Application of stack, queueStack: Expression evaluation

    a*(bc)/d => abc*d/Queue: priority queues

  • Exercise:Implement: 5 sort algorithmsImplement stack, queue using array

    Menu with 4 choicesAdd, remove, display, exit

  • Week 6: V vic kim tra gia kPhn nhm thc hnh lm 2 caim di 5 thNi dung

  • Week 6: n tp functionOn return value

    Void FunctionsReturn FunctionExample: void display(); int max(int a,int b);On Parameters

    value parameters reference parametersExmple: void swap(int &a, int &b); int BinhPhuong(int n);

  • Week 6: n tp functionNothing return

    void

  • Week 6: n tp functionReturn 1 value

    intreturn

  • Week 6: n tp functionReturn many value

    voidintreference parameters

    return

    On natural way

  • Week 6: n tp functionExample

    ??? FindMax(3 numbers ???) ??? FindMin(3 numbers ???)??? TinhChuVi_ChuNhat (????)??? TinhChuVi__DienTich_ChuNhat (????)??? GiaiPT_bac_1 (???)??? GiaiPT_bac_2 (???)??? Sum_of_array(???)??? FindElement_in_array(???)

  • Week 6: Linked ListTHE CONCEPT OF THE LINKED LISTSINGLE LINKED LISTDOUBLE LINKED LIST CIRCULAR LINKED LIST

  • THE CONCEPT OF THE LINKED LISTthe size requirement need not be known at compile time A linked list is a data structure that is used to model such a dynamic list of data items, so the study of the linked lists as one of the data structures is important.

  • Array and LINKED LISTARRAY

    sequential mapping, elements are fixed distance apart makes insertion or deletion at any arbitrary position in an array a costly operation Linked List

    not necessary that the elements be at a fixed distance apart an element is required to be linked with a previous element of the list done by storing the address of the next element

  • Array and LINKED LIST

    0123456X

    X

    X

    X

    Array: max length=70123456X789X1011X121314X15161718Linked List: max length=180123456Get element by order number

  • Type of Linked ListdataLinkdataLinkNULLdataLinkdataLinkdataLinkLinkdataLinkLinkdataLinkLinkdataLinkLinkdataLinkLink1234

  • 4 things when building Linked List1. Structure

    Data elementLink field element2. The way to make link between elements

    First, last, middle element3. How many node to take all list elements, how to take all list4. Basic operations:

    Insert new element (every position)Delete (every position)FindNotes: Check value change in step 3

  • 2.Singly Linked ListdataLinkdataLinkNULL1. Structure

    Data elementLink field element2. The way to make link between elements

    First, last, middle element3. How many node to take all list elements , how to take all list4. Basic operations:

    Insert new element (every location)Delete (every position)Find

  • 2.Singly Linked List1. Structure

    struct Node{int data;Node *link;};

  • 2.Singly Linked List1. Structure: how to use one node

    Node a;

    a.data=10;a.link=NULL;

    coutlink=NULL;cout

  • 2.Singly Linked List2. The way to make link between elements

    First, last, middle elementdataLinkNULLdataLinkdataLinkdataLink

    HeadMiddleLast

  • 2.Singly Linked List3. How many node to take all list elements, how to take all list

    dataLinkNULLdataLinkdataLinkdataLink

    pHeadWhy+from pHead, can we list all items?+from pHead, can we do everything with list: insert new, delete?+Do we need pTail?

    pTail

  • 2.Singly Linked List3. How many node to take all list elements, how to take all list

    dataLinkNULLdataLinkdataLinkdataLink

    pHeadHow to store pHead, pTailpTailType 1: Node *pHead=NULL, *pTail=NULL;Type 2: typedef struct Node *List;List pHead, pTail;

    *#include

    typedef struct Node *List;struct Node{int data;Node *link;};

    void change(List &a){a=new Node();cout

  • 2.Singly Linked List4. Basic operations:

    dataLinkNULLpdataLinkdataLinkcreating new nodeInsert nodeRemove node

  • 2.Singly Linked List4. Basic operations: creating new node

    dataLinkNULLpNode * createNewNode(int X){Node *p=new Node;If (p!=NULL){p->data=X;p->link=NULL;}return p;}

  • 2.Singly Linked List: using Phead onlyvoid addnodeatFirst(node *newnode){if (pHead==NULL){ pHead =newnode;}else{newnode->next=pHead; pHead =newnode;}}Insert Node at First

    *#include #include #include

    void menu();

    struct node{int data;node *next;};

    node *h=NULL;

    void removeatlast(){node *t=h;node *truoc=t;while (t->next!=NULL){truoc=t;t=t->next;}

    truoc->next=NULL;delete t;}void insertatlast(node *newnode){node *t=h;while (t->next!=NULL)t=t->next;

    t->next=newnode;}

    //============================node *find(int data){node *temp=h;while (temp!=NULL && temp->data!=data)temp=temp->next;return temp;}//===========================void xoanodedau(){if (h!=NULL){node *t=h;h=h->next;delete t;}}//============================node* taonode(int data){node *n=new node();if (n!=NULL){n->data=data;n->next=NULL;}return n;}//==================================void addnode(node *newnode){if (h==NULL){h=newnode;}else{newnode->next=h;h=newnode;}}//===================================void displaylist(){node *temp=h;while (temp!=NULL){coutl;switch (l){case 1:int k;coutk;node* X; X=taonode(k);addnode(X);break;//case 2://break;

    case 3:displaylist();getch();break;case 4:xoanodedau();break;case 5:node* X1;int f;coutf;X1=find(f);if (X1==NULL)cout

  • 2.Singly Linked List: using Phead onlyvoid displaylist(){node *temp=h;while (temp!=NULL){cout
  • 2.Singly Linked List: using Phead onlyvoid RemoveNodeatFirst(){if (pHead!=NULL){node *t= pHead; pHead = pHead ->next;delete t;}}Remove Node at First

  • 2.Singly Linked List: using Phead onlynode *find(int key){node *temp=h;while (temp!=NULL && temp->data!=key)temp=temp->next;return temp;}Find Node

  • 2.Singly Linked List: using Phead onlyvoid removeatlast(){node *t=h;node *truoc=t;while (t->next!=NULL){truoc=t;t=t->next;}

    truoc->next=NULL;delete t;}Remove Node at Last

  • 2.Singly Linked List: using Phead onlyvoid insertatlast(node *newnode){node *t=h;while (t->next!=NULL)t=t->next;

    t->next=newnode;}Insert Node at Last

  • 2.Singly Linked List:using pHead & pTail4. Basic operations: Insert new node

    dataLinkdataLinkdataLinkdataLinkNULLpHeadpTail

  • 2.Singly Linked List4. Basic operations: Insert new node at First

    void Insert_First (node *newnode){ if ( pTail == NULL ) { pHead=pTail =newnode ; } else { newnode->next=pHead ; pHead=newnode; }}

  • 2.Singly Linked List4. Basic operations: Insert new node at Last

    void Insert_Last (node *newnode){ if ( pTail == NULL ) { pHead=pTail =newnode ; } else { pTail>next=newnode ; pTail=newnode; }}

  • 2.Singly Linked List4. Basic operations: Insert new node after node

    void Insert_after (node *newnode,node *p){If (p!=pTail) { newnode->next=p>next; p->next=newnode;}else insert_Last (newnode); }

  • 2.Singly Linked List4. Basic operations: remove node at First

    void removeNodeAtFirst (){If (pHead!=NULL){ Node *temp=pHead; pHead = pHead >next; delete temp;}}

  • 2.Singly Linked List4. Basic operations: remove node after

    void removeNodeAfter (node *p){ Node *temp=p>next; p->next=p->next->next; delete temp;}

  • 2.Singly Linked List4. Basic operations: remove node at Last

    void removeNodeatLast (){???}

  • 2.Singly Linked List4. Basic operations: Seek all nodes

    Void Display(){node *p=pHead;while (p!=NULL) {cout

  • 2.Singly Linked List4. Basic operations: count number of nodes

    int Count (){int count=0;node *p=pHead;while (p!=NULL) { count+=1; p=p->next; }return count;}

  • 2.Singly Linked List4. Basic operations: Remove List

    Remove pHead nodeDo until pHead is NULL

  • 2.Singly Linked List: DemoWrite a program for buiding single linked list: using pHead only

    Display menuAdd one node at firstAdd one node at lastAdd many node at firstAdd many node at lastSelect and display n(th) nodeFind one nodeAdd one node after select nodeDisplay node countDisplay ListRemove one nodeRemove ListGet sum of all nodes

  • Week 7Find nodeSingle linked list: pHead and pTailCircular single linked listDouble Linked List

  • Find NodeUsing WhileUsing Loop

  • Find Node: using while loopNode* temp; //Node *temp=new Node();???temp=pHead;while (temp->data!=Xvalue)temp=temp->next;=========================================Node* temp; //Node *temp=new Node();???temp=pHead;while (temp!=NULL && temp->data!=Xvalue)temp=temp->next;ExactlyMay be not found

  • Find Node: using for loopfor (Node* temp=pHead;temp->data!=Xvalue; temp=temp->next);

  • 3.Singly Linked List: pHead and pTailSame to manage list with pHeadTake care: cases change pTail

    Add nodeRemove Node

  • 3.Singly Linked List: pHead and pTailWhen pTail is changed?

    Insert new node at firstdataLinkpTail=NULLpHead =pHead=pTailHow to check ?dataLinkdataLinkpHeadpTail

  • 3.Singly Linked List: pHead and pTailWhen pTail is changed?

    Insert new node at LastdataLinkpTail=NULLpHead =pHead=pTailHow to check ?dataLinkdataLinkpHeadpTail

  • 3.Singly Linked List: pHead and pTailWhen pTail is changed?

    Insert new node after one nodedataLinkpTail=NULLpHead =pHead=pTailHow to check ?dataLinkdataLinkpHeadpTaildataLink

  • 3.Singly Linked List: pHead and pTailWhen pTail is changed?

    Remove nodedataLinkpTail=NULLpHead =pHead=pTailHow to check ?dataLinkdataLinkpHeadpTaildataLink

  • 3.Singly Linked List: pHead and pTailExample:

    Write function to insert at lastSingle linked list with pHead and pTail

  • 4. Circular single linked listCircular

    Last node point to first nodeDraw like CircleWhen using Circular single linked list

    Every node in list had the same positionNeednt Head, Tail

  • 4. Circular single linked listControl Circular single linked list: Insert node

    dataLinkpHead =NULLpHeadHow to check ?dataLinkdataLinkpHeaddataLink

  • 4. Circular single linked listControl Circular single linked list: Insert node steps

    dataLinkdataLinkpHeaddataLinkdataLinkdataLinkdataLinkdataLinkdataLinkdataLinkdataLinkdataLinkdataLink

  • 4. Circular single linked listControl Circular single linked list: Remove node

    dataLinkpHead =NULLpHeadHow to check ?dataLinkdataLinkpHeaddataLink

  • 4. Circular single linked listExample:

    Write function to remove a node Circular single linked list with pHead and pTail

  • 4. Double Linked ListStruct Node{Int data;Node *next;Node * pre;};

  • 4. Double Linked ListInsert new node

    First, Last, after nodeRemove node

    First,Last, at one middle node

  • data

    data

    data

    4. Double Linked ListInsert new node: after one Node First steps

    data

    data

    data

    data

    data

    data

    data

    data

    data

  • 4. Double Linked ListRemove node: steps

    data

    data

    data

    data

    data

    data

    data

    data

    data

    data

    data

    data

  • 4. Double Linked ListExample

    Write function to remove first node (pHead)Write function to insert a node after another node

  • Week 8ExercisesReview: FileReview: StringExcercises

  • Review C/C++ programming1. Working with string2. Working with file: read/write file3. Exercise 6

  • 1. String: structure

    String

    is array of charEnding with null char \0 (size +1)Example: store 10 chars:char str[11];Example: string const. C/C++ add \0 automayically

  • 1. String: declare

    Declare string

    Using array of charschar str[] = {H,e,l,l,o,\0}; //declare with nullchar str[] = Hello; //neednt nullUsing char pointerchar *str = Hello;

  • 1. String: inputchar *gets(char *s);

    Read every charUntil receive Enter Adding Automatically \0cin>>s;

  • 1. String: outputint puts(const char *s);cout
  • 1. String: Problem with buffer?Keyboard buffer

    char szKey[] = "aaa"; char s[10]; do { cout

  • 1. String: functions#include strcpy(s1, s2)strcat(s1, s2)strlen(s1)strcmp(s1, s2) -> (-1,0,1)strchr(s1, ch)strstr(s1, s2)

  • 1. String: function exampleschar s1[80], s2[80];cout
  • 2. File: Creating a new file #include FILE *fp;fp=fopen(d:\\test.txt", "wb"))fwrite(&Address, sizeof(TYPE), count, fp);fclose(fp);

  • 2.File: Creating a new file

    int Arr[3]ArrFwrite(Arr, sizeof(int), 1, fp);fwrite(Arr, sizeof(Arr), 1, fp);Fwrite(&Arr[i], sizeof(int), 1, fp);for (i=0;i

  • 2. File: Reading a file#include FILE *fp;fp=fopen(d:\\test.txt", rb"))while (fwrite(&Address, sizeof(TYPE), count, fp)){

    .}fclose(fp);

    *#include #include #include #include #include #include #include "node.cpp"

    void menu(){clrscr();cout

  • 3.ExcercisesExercise 6

  • Week 9: Tree1. THE CONCEPT OF TREES2. BINARY TREE AND REPRESENTATION3. BINARY TREE TRAVERSAL4. BINARY SEARCH TREE

  • 1. THE CONCEPT OF TREESA tree is a set of one or more nodes T:

    there is a specially designated node called a rootThe remaining nodes are partitioned into n disjointed set of nodes T1, T2,,Tn, each of which is a tree.

  • 1. THE CONCEPT OF TREESExample

  • 1. THE CONCEPT OF TREESIts not a tree

    Tree

  • 1. THE CONCEPT OF TREES: Some terminologyRootChild (left,right)ParentLeaf nodeSubtreeAncestor of a nodeDescendant of a node

  • 1. THE CONCEPT OF TREESDegree of a Node of a Tree

    The degree of a node of a tree is the number of subtrees having this node as a root. Degree of a Tree

    The degree of a tree is defined as the maximum of degree of the nodes of the treeLevel of a Node

    level of the root node as 1, and incrementing it by 1 as we move from the root towards the subtrees.

  • 2. BINARY TREE AND REPRESENTATION BINARY TREE

    no node can have a degree of more than 2. The maximum number of nodes at level i will be 2i1 If k is the depth of the tree then the maximum number of nodes that the tree can have is2k 1 = 2k1 + 2k2 + + 20

  • 2. BINARY TREE AND REPRESENTATION BINARY TREE

    A full binary tree is a binary of depth k having 2k 1 nodes. If it has < 2k 1, it is not a full binary tree

  • What is the height h of a full tree with N nodes?

    The max height of a tree with N nodes is N (same as a linked list)The min height of a tree with N nodes is log(N+1)

  • 2. BINARY TREE AND REPRESENTATION

    3=22-17=23-115=24-1full binary

  • 2. BINARY TREE AND REPRESENTATIONstruct node{ int data;node *left;node *right;};

  • Tree traversalUsed to print out the data in a tree in a certain order

    inorder (LDR )Postorder (LRD ) preorder (DLR )Pre-order traversal

    Print the data at the rootRecursively print out all data in the left subtreeRecursively print out all data in the right subtree

  • Preorder, Postorder and InorderPreorder traversal

    node, left, rightprefix expression++a*bc*+*defg

  • Preorder, Postorder and InorderPostorder traversal

    left, right, nodepostfix expressionabc*+de*f+g*+

    Inorder traversal

    left, node, right.infix expressiona+b*c+d*e+f*g

  • Preorder, Postorder and Inorder

  • 3. BINARY TREE TRAVERSAL

  • 3. BINARY TREE TRAVERSALInorder = DBEACMany trees

  • 4. BINARY SEARCH TREEA binary search tree

    is a binary tree (may be empty)every node must contain an identifier. An identifier of any node in the left subtree is less than the identifier of the root. An identifier of any node in the right subtree is greater than the identifier of the root. Both the left subtree and right subtree are binary search trees.

  • 4. BINARY SEARCH TREEbinary search tree.

  • Binary Search Trees

    A binary search treeNot a binary search tree

  • Binary search trees

    Two binary search trees representing the same set: Why?

  • PerformanceConsider a dictionary with n items implemented by means of a binary search tree of height h

    the space used is O(n)methods find, insert and remove take O(h) timeThe height h is O(n) in the worst case and O(log n) in the best case

  • 4. BINARY SEARCH TREEWhy using binary search tree

    traverse in inorder: sorted listsearching becomes faster

    But..

    Insert, delete: slowImportant thing: Index in Database system

    Using the right way of Index property

  • SearchTo search for a key k, we trace a downward path starting at the rootThe next node visited depends on the outcome of the comparison of k with the key of the current nodeIf we reach a leaf, the key is not found and we return nukkExample: find(4):

    Call TreeSearch(4,root)Algorithm TreeSearch(k, v)if (v ==NULL)return vif k < key(v)return TreeSearch(k, T.left(v))else if k = key(v)return velse { k > key(v) }return TreeSearch(k, T.right(v))6924

    1

    8

    =

    *

  • InsertionTo perform operation inser(k, o), we search for key k (using TreeSearch)Assume k is not already in the tree, and let let w be the leaf reached by the searchWe insert k at node w and expand w into an internal nodeExample: insert 5

    6924

    1

    8

    6924

    1

    8

    5

    >ww

  • 4. BINARY SEARCH TREEInsert new node

  • 4. BINARY SEARCH TREEInsert new node

    void InsertNode(node* &root,node *newnode){if (root==NULL)root=newnode;elseif (root->data>newnode->data)InsertNode(root->l,newnode);else if (root->datadata)InsertNode(root->r,newnode);}

  • Insert node

  • Insert node

  • Insert Order

  • 4. BINARY SEARCH TREEtraverse node

    void preorder(node* r){if (r!=NULL){cout

  • 4. BINARY SEARCH TREEtraverse node

  • 4. BINARY SEARCH TREEtraverse node

  • Exercise 11. Build Binary Search Tree from list

    10 4 7 12 16 20 30 5 2 26 15 24 12 89 4 32 50 10 6 36 79 5 9 11

  • Exercise 21. Order of: inoder, postorder, preorder of

  • Exercise 31. Order of: inoder, postorder, preorder of

  • Week 10Search nodeCount

    Even/OddLeafSum

    Even/OddHeightDelete node

  • 1. SEACRCHING NODEnode* search(node* &r, int data){if (r==NULL)return NULL;else if (r->data==data)return r;elseif (datadata)return search (r->l,data);elseif (data>r->data) return seach(r->r,data);

    }

  • 1. SEACRCHING NODEnode* search(node* &r, int data){if ( (r==NULL) || (r->data==data) )return r;elseif (datadata)return search (r->l,data);elseif (data>r->data) return seach(r->r,data);

    }100H20H4080NULLNULLH3H20120NULLNULLH40Node* S=search(r,80)What does S stand for?

  • 2. COUNTING THE NUMBER OF NODESint count(struct tnode *p)

    { if( p == NULL) return(0); else if( p->lchild == NULL && p->rchild == NULL) return(1); else return(1 + (count(p->lchild) + count(p->rchild)));

    }

    With RecursionWithout Recursion

  • 2. COUNTING THE NUMBER OF NODESint count(struct tnode *p)

    { if( p == NULL) return(0); else return(1 + (count(p->lchild) + count(p->rchild)));

    }

  • 3. Sum of all nodesint sum(node *p)

    { if( p == NULL) return(0); else return( p->data+sum(p->l)+sum(p->r) ); }

  • 4. COUNTING THE NUMBER OF EVEN (ODD) NODESint counteven(node* r){if (r!=NULL)if (r->data%2==0)return 1+ counteven(r->l)+counteven(r->r);elsereturn counteven(r->l)+counteven(r->r);elsereturn 0;}

  • 5. SUM OF EVEN (ODD) NODESint counteven(node* r){if (r!=NULL)if (r->data%2==0)????????????????????else????????????????????elsereturn 0;}

  • 6. Count number of leaf nodesExercise

    Count number of leaf nodes

  • 6. Count number of leaf nodesint countleaf(node* r){if (r!=NULL)if (r->l==NULL && r->r==NULL)return 1;elsereturn countleaf(r->l)+countleaf(r->r);elsereturn 0;}

  • 6. Count number of node had 1 childint count1child(node* r){if (r!=NULL)if (????????????????????????????)return 1+count1child(r->l)+count1child(r->r);elsereturn count1child(r->l)+count1child(r->r);elsereturn 0;}

  • 6. Count number of node had 2 childrenint count2child(node* r){if (r!=NULL)if (????????????????????????)return 1+count2child(r->l)+count2child(r->r);elsereturn count2child(r->l)+count2child(r->r);elsereturn 0;}

  • 7. Find height of treeint Height (node* n){if(n==NULL) return 0;else return 1+max(Height (n->l)), Height (n->r));}

  • 8. Delete nodeDivide into 3 cases

    Deletion of a Node with No ChildDeletion of a Node with one ChildDeletion of a Node with two Children

    *void del(node* &n){if (n->l==NULL){node* temp=n;n=n->r;delete temp;}else if(n->r==NULL){coutl;delete temp;}else{node *temp=n->r;node*parent=n;while (temp->l!=NULL){parent=temp;temp=temp->l;}n->data=temp->data;if (temp==parent->l)del(parent->l);elsedel(parent->r);}}

    void del1(node* &n,int tim){if (n==NULL) return;if (n->datar,tim);else if (n->data>tim)del1(n->l,tim);else //bangdel(n);

    }

  • 8. Delete node Deletion of a Node with No Child

    Set the left of y to NULLDispose of the node pointed to by x

  • 8. Delete nodeDeletion of a Node with One Child

    Make the y->left=x->rightdispose of the node pointed to by x

  • 8. Delete nodeDeletion of a Node with two Children

    *void DeleteNode(Node * & node) { if (node->left == NULL) { Node *temp = node; node = node->right; delete temp; } else if (node->right == NULL) { Node *temp = node; node = node->left; delete temp; } else { // In-order predecessor (rightmost child of left subtree) // Node has two children - get max of left subtree Node *temp = node->left; // get left node of the original node Node *parent = node; // find the rightmost child of the subtree of the left node while (temp->right != NULL) { parent = temp; temp = temp->right; } // copy the value from the in-order predecessor to the original node node->value = temp->value; // now delete the "swapped" node value and unlink // the "deleted" node from the parent (via recursion)if(parent->left == temp) { _DeleteNode(parent->left);} else { _DeleteNode(parent->right);} }}

  • 8. Delete noderightmost child of the subtree of the leftleftmost child of the subtree of the right But WHY???

  • Deletion (cont.)We consider the case where the key k to be removed is stored at a node v whose children are both internal

    we find the internal node w that follows v in an inorder traversalwe copy key(w) into node vwe remove node w and its left child z (which must be a leaf) by means of operation removeExternal(z)Example: remove 3

    3186

    9

    5

    vwz2

    5186

    9

    v2

  • Deletion (cont.): exercise1: remove 16

  • Deletion (cont.): exercise1: remove 16

  • Deletion (cont.): exercise2: remove 16

  • Deletion (cont.): exercise2: remove 16

  • Exercise:Write program to delete node

    *#include #include #include struct node{int data;node *l,*r;};typedef struct node* NODE;void del(node* &n);void del1(node* &n,int tim);

    int height(node* r){if (r==NULL)return 0;elsereturn 1+max(height(r->l),height(r->r));}

    void display(node* r){if (r!=NULL){display(r->l);coutr);elsereturn 0;}

    int counteven(node* r){if (r!=NULL)if (r->data%2==0)return 1+ counteven(r->l)+counteven(r->r);elsereturn counteven(r->l)+counteven(r->r);elsereturn 0;}

    int menu(){clrscr();coutdata)timthay=n;else if (datadata)search2 (n->l,data);else if (data>n->data) search2(n->r,data);}}

    int countleaf(node* r){if (r!=NULL)if (r->l==NULL && r->r==NULL)return 1;elsereturn countleaf(r->l)+countleaf(r->r);elsereturn 0;}

    node* r=NULL;

    void nhap(){int a[]={12,8,16,6,10,13,20,14,19,24,17,18};for (int i=0;i

  • Week 13AVL Tree

  • AVL tree property

    An AVL tree is a binary search tree with theadditional AVL tree property : For any node x, the heights of left(x) and right(x) differ by at most 1.15

    10

    20

    23

    3

    18

    1NOT an AVL tree. Why?

    AVL trees

    *

  • AVL TreeBTSWhere did it come from?two inventors, G.M. Adelson-Velsky and E.M. Landis1962 paper "An algorithm for the organization of information." Why?Fast search, delete, insert 0(logn);OperationInsertDeleteLook up

  • balance factor

    height of its right subtree minus the height of its left subtree 10-1

    *

  • Rotations

    The insert and delete operations of AVL tree are the same as binary search tree (BST).

    Since an insertion (deletion) involves adding (deleting) a tree node, this can only increase (decrease) the heights of some subtree(s) by 1.

    Thus, the AVL tree property may be violated.

    If the AVL tree property is violated at a node x, it means that the heights of left(x) and right(x) differ by exactly 2.

    *

  • Rotations

    After the insertion or deletion operations, we need to examine the tree and see if any node violates the AVL tree property.If the AVL tree property is violated at node x, single or double rotation will be applied to x to restore the AVL tree property.Rotation will be applied in a bottom-up manner starting at the place of insertion (deletion). Thus, when we perform a rotation at x, the AVL tree property is restored at all proper descendants of x. This fact is important.

    *

  • Rotations

    *

  • Insertion

    Perform normal BST insertion.

    Check and restore AVL tree property.Trace from path of inserted leaf towards the root, and check if the AVL tree property is violated.Check to see if heights of left(x) and right(x) height differ by at most 1.If the AVL tree property is violated, there are 4 rotation cases to restore the AVL tree property.

    *

  • Insertion

    *

  • Restore AVL tree property Case 1

    If the AVL tree property is violated at x, let the height of x be h+3 :If the height of left(x) is h+2 thenCase 1: If the height of left(left(x)) is h+1, we single rotate with left child.

    *

  • Restore AVL tree property Case 1

    Case 1 : Single rotate with left child.h+3h+2h+2h+3

    *

  • Restore AVL tree property Case 1

    Case 1 : Single rotate with left child

    *

  • Restore AVL tree property Case 1

    Case 1 : Single rotate with left child.

    *

  • Restore AVL tree property Case 2

    If the AVL tree property is violated at x, let the height of x be h+3 :If the height of left(x) is h+2 thenCase 1: If the height of left(left(x)) is h+1, we single rotate with left child. Case 2: Otherwise, the height of right(left(x)) is h+1, then we double rotate with left child.

    *

  • Restore AVL tree property Case 2

    Case 2 : Double rotate with left child.h+2h+3

    *

  • Restore AVL tree property Case 2

    Case 2 : Double rotate with left child.

    *

  • Restore AVL tree property Case 2

    Case 2 : Double rotate with left child.

    *

  • Restore AVL tree property Case 3

    If the AVL tree property is violated at x, let the height of x be h+3 :If the height of left(x) is h+2 thenCase 1: If the height of left(left(x)) is h+1, Case 2: Otherwise, the height of right(left(x)) is h+1, then we double rotate with left child.Otherwise, height of right(x) is h+2Case 3: (Mirror image of the case 1) If the height of right(right(x)) is h+1, then we single rotate with right child. Case 4: (Mirror image of the case 2) Otherwise, the height of left(right(x)) is h+1, then we double rotate with right child.

    *

  • Restore AVL tree property Case 3

    Case 3 : Single rotate with right child.

    *

  • Restore AVL tree property Case 3

    Case 3 : Single rotate with right child.

    *

  • Restore AVL tree property Case 4

    If the AVL tree property is violated at x, let the height of x be h+3 :If the height of left(x) is h+2 thenCase 1: If the height of left(left(x)) is h+1, Case 2: Otherwise, the height of right(left(x)) is h+1, then we double rotate with left child.Otherwise, height of right(x) is h+2Case 3: (Mirror image of the case 1) If the height of right(right(x)) is h+1, then we single rotate with right child. Case 4: (Mirror image of the case 2) Otherwise, the height of left(right(x)) is h+1, then we double rotate with right child.

    *

  • Restore AVL tree property Case 4

    Case 4 : Double rotate with right child.h+2

    *

  • Restore AVL tree property Case 4

    Case 4 : Double rotate with right child.

    *

  • Insertion

    Trace from path of inserted leaf towards the root, and check if the AVL tree property is violated. Perform rotation if necessary.

    For insertion, once we perform (single or double) rotation at a node x, the AVL tree property is already restored. We need not to perform any rotation at any ancestor of x.Why???Thus one rotation is enough to restore the AVL tree property.There are 4 different cases (actually 2), so dont mix up them!

    *

  • Insertion

    The time complexity to perform a rotation is O(1).

    The time complexity to insert, and find a node that violates the AVL property is dependent on the height of the tree, which is O(log(n)).

    So insertion takes O(log(n)).

    *

  • Deletion

    Delete a node x as in ordinary BST (Note that x is either a leaf or x has exactly one child.).

    Check and restore the AVL tree property.

    Trace from path of deleted node towards the root, and check if the AVL tree property is violated.

    Similar to an insertion operation, there are four cases to restore the AVL tree property.

    *

  • Deletion

    The only difference from insertion is that after we perform a rotation at x, we may have to perform a rotation at some ancestors of x. It may involve several rotations.

    Therefore, we must continue to trace the path until we reach the root.

    The time complexity to delete a node is dependent on the height of the tree, which is also O(log(n)).

    *

  • Deletion : no rotation

    No need to rotate.

    *

  • Deletion : one rotation

    Case 3 : Single rotate with right child.

    *

  • Deletion : several rotations

    Case 3 : Single rotate with right child.Case 4 : Double rotate with right child.

    *

  • Summary of AVL Trees

    Maintains a balanced tree by posing an AVL tree property:guarantees the height of the AVL tree be O(log n)implies that functions search, min, and max, insert, and delete will be performed in O(logn)Modifies the insertion and deletion routinePerforms single or double rotation to restore the AVL tree property if necessary.Requires a little more work for insertion and deletion.

    *

  • Exercise 1

    a. Insert 3???

    *

  • An: Exercise 1

    a. Insert 3

    *

  • Exercise 2

    a. Insert 5???

    *

  • An. Exercise 2

    a. Insert 5

    *

  • Exercise 3

    Insertion order:10, 85, 15, 70, 20, 60, 30, 50, 65, 80, 90, 40, 5, 55???

    *

  • An Exercise 3

    Insertion order:10, 85, 15, 70, 20, 60, 30, 50, 65, 80, 90, 40, 5, 55

    *

  • Exercise 4

    Delete 40

    *

  • An. Exercise 4

    Delete 40

    *

  • An. Exercise 4

    Delete 40

    *

  • Exercise 5

    Delete 20

    *

  • An. Exercise 5

    Delete 20

    *

  • Week 14Sa bi tp

  • Exercise 1 /S 4T chc v xy dng 2 hm :GiiPT_bac1GiiPT_bac2

    Tnh ng gi?

    abx1Trng hp

    abxTrng hpcx2

  • Exercise 3 /S 4Vit chng trnh tnh lng cho cc cng nhn ti xng may. Mi cng nhn s c gi vo v gi ra trong mt ngy. Tin lng c tnh nh sau:T 5h-8h: mi gi 20,000 T 8h-11h: mi gi 15,000 T 11h-14h: mi gi 30,000 T 14h-17h: mi gi 22,000 T 17h-24h: mi gi 40,000

  • Exercise 3 /S 45811141724

  • Exercise 3 /S 45811141724Double TinhTien(c1,c2,v1,v2,dongia)c1c2v1v2

  • Exercise 3 /S 41114Double TinhTien(c1,c2,v1,v2,dongia)c1c2v1v2V1c1 && V1c2

  • Bi tp 1 /S 10Sinh vin:+M SV: char[10];+M Lp : int+Tn SV: char[255];+DiemToan+DiemLy+DiemHoaLp gm cc thng tin: +M Lp: int+Tn Lp: char[10];+Kha

  • 1NCD1A123Nguyn Th NhLp: 1im: 9,8,10Struct lop{ int ma;Ten char[20];};Struct SV{ char ma[10];Ten char[20];Int malop;Double toan,ly,hoa;};1Tree - 1Tree1

  • 1NCD1A123Nguyn Th NhLp: ?im: 9,8,10Struct lop{ int ma;Ten char[20];

    Lop* left,right;};Struct SV{ char ma[10];Lop* lop;Int malop;Double toan,ly,hoa;SV* left,right;};1Tree - 1Tree2

  • 1NCD1A123Nguyn Th NhLp: ?im: 9,8,10Struct lop{ int ma;Ten char[20];SV *ListSV;Lop* left,right;};Struct SV{ char ma[10];Double toan,ly,hoa;SV* left,right;};1Tree - nTree

    3

  • 1NCD1A123Nguyn Th NhLp: ?im: 9,8,10Struct lop{ int ma;Ten char[20];SV* listSV;Lop* left,right;};Struct SV{ char ma[10];Double toan,ly,hoa;SV* next;};Tree Single Linked List

    4

  • 1NCD1A123Nguyn Th NhLp: ?im: 9,8,10Struct lop{ int ma;Ten char[20];SV* listSV;Lop* left,right;};Struct SV{ char ma[10];Double toan,ly,hoa;SV* next,pre;};Tree Double Linked List

    5

  • 1NCD1A123Nguyn Th NhLp: ?im: 9,8,10Struct lop{ int ma;Ten char[20];SV* listSV;Lop* next,pre;};Struct SV{ char ma[10];Double toan,ly,hoa;SV* next,pre;};Double Linked List Double Linked List

    5

  • Bi tp ti lpQun l mua v hnh khchV my bay (ID,gi)Khch(PassID, ten)Mi khch ch mua 1 v

    1Tree-1Tree1Tree-1 single L.L1Tree-1 double L.L1double LL-1Tree1double LL-1 Double L.L

  • Week 15Some Final Test questionsProblems only

  • Part 1: Basic Programming

  • 1What will be the output of the following code?

    int x, y, z; x=1; y=2; z=3; int* a = &x; *a = y; cout

  • 1GWhat will be the output of the following code?

    int x, y, z; x=1; y=2; z=3; int* a = &x; *a = y; cout

  • 2After execution of the statement:

    char *p = "Stuff";

    what would be printed by following statement?

    printf("%c",*p+3);SVUFu

  • 2GAfter execution of the statement:

    char *p = "Stuff";

    what would be printed by following statement?

    printf("%c",*p+3);V

  • 3i=5 j=10i = 5, j = 5i=10, j = 5Nothing. The program will most likely crash.What is the output of the following program?

    int main () {int i, j, *p, *q;p = &i;q = &j;*p = 5;*q = *p + i; printf("i = %d, j = %d\n", i, j);}

  • 3Gi=5 j=10What is the output of the following program?

    int main () {int i, j, *p, *q;p = &i;q = &j;*p = 5;*q = *p + i; printf("i = %d, j = %d\n", i, j);}

  • 4If this code fragment were executed in an otherwise correct and complete program, what would the output be?

    int a = 3, b = 2, c = 5if (a > b)a = 4;if ( b > c)a = 5;elsea = 6;cout

  • 4gIf this code fragment were executed in an otherwise correct and complete program, what would the output be?

    int a = 3, b = 2, c = 5if (a > b)a = 4;if ( b > c)a = 5;elsea = 6;cout

  • 5int whatIsIt (int x, int n){if ( n == 1 ) return x;elsereturn x * whatIsIt(x, n-1);}What is the value returned by whatIsIt(4, 4)?

    25664416128

  • 5gint whatIsIt (int x, int n){if ( n == 1 ) return x;elsereturn x * whatIsIt(x, n-1);}What is the value returned by whatIsIt(4, 4)?

    256

  • 7What is the output of the following program?

    #include

    int * f(int * p, int & x){ ++x; p = &x; return p; }

    int main( ){int x = 2, y = 5;int * p = &y;int * q = f(p, x);cout

  • 7gWhat is the output of the following program?

    #include

    int * f(int * p, int & x){ ++x; p = &x; return p; }

    int main( ){int x = 2, y = 5;int * p = &y;int * q = f(p, x);cout

  • 8Giving code segment:

    void mangle_numbers(int &a, int b){int c,d,e;a = 3;b = a+2;c = b++;d = ++b;e = a+5;b *=5;}void main(){int sum,x=5, y=7;mangle_numbers(x,y);sum=x+y;}After running code segment, value of sum is:

    9----------------8----------------10----------------12

  • 8gGiving code segment:

    void mangle_numbers(int &a, int b){int c,d,e;a = 3;b = a+2;c = b++;d = ++b;e = a+5;b *=5;}void main(){int sum,x=5, y=7;mangle_numbers(x,y);sum=x+y;}After running code segment, value of sum is:

    10

  • 9After the following code:

    int i = 2; int k = 4; int *p1; int *p2; p1 = &i; p2 = &k; p1 = p2; *p1 = 6; *p2 = 8;

    what is the value of i and k

    2 8----------------4 2----------------6 8----------------2 4

  • 9gAfter the following code:

    int i = 2; int k = 4; int *p1; int *p2; p1 = &i; p2 = &k; p1 = p2; *p1 = 6; *p2 = 8;

    what is the value of i and k

    2 8

  • 10If myAge, a, and b are all int variables, what are their values after this sample program executes?

    myAge = 39; a = myAge++; b = ++myAge;

    myAge: 39, a: 39, b: 39----------------myAge: 39, a: 39, b: 40----------------myAge: 41, a: 39, b: 41----------------myAge: 39, a: 40, b: 41

  • 10gIf myAge, a, and b are all int variables, what are their values after this sample program executes?

    myAge = 39; a = myAge++; b = ++myAge;

    myAge: 41, a: 39, b: 41

  • Part 2: Recursion

  • 6What does the following program output?

    #include int test(int n){if(n

  • 6gWhat does the following program output?

    #include int test(int n){if(n

  • 7gint f(int x[], int n);void main(){int a[5] = {1, 2, 3, 4, 5};int b;b = f(a, 5);}int f(int x[], int n){if (n == 1)return x[0];elsereturn x[n 1] + f(x, n 1);}

    After running code segment, value of b is

    15

  • 8gGiving code segment:

    int f( int n ){ if ( n==1 ) return 1; else return ( f(n-1)+n );}

    Select return result when call: f(101)?

    5151

  • 9gpublic int mystery(int k, int n){if (n==k)return k;else if (n > k)return mystery(k, n-k);elsereturn mystery(k-n, n);}

    Based on the method defined, what is the value of mystery(6,8)?

    2

  • 10gSuppose that the following function.

    int sss(int x) { if (x % 2 == 0) return x+1; else return (x - 1)*sss(x + 1); }

    Determine the output of the following statement.

    println(sss(3));

    10

  • 11gThe following function.

    static int ttt(int x, int y) { if (x % y == 0) return x/y + 2; else return x - ttt(y, x + 1); }

    Determine the output of the following statement.

    println(ttt(7, 3));

    8

  • 12gThe following function.

    int kkk(int x){ if((x % 3 == 0) && (x > 0)) return 1 + kkk(4 + kkk(x - 3)); else if (x % 2 == 0) return kkk(x + 1); return x + 2; }

    What value would the call kkk(2) return?

    10

  • 13gint Wow (int n ,m ) { if (m ==1) return n; if ( n == m)return 1; return (Wow(n - 1, m - 1) + Wow (n - 1 , m); } Wow(5 , 2) will return which of the following?

    10

  • Part 3: search - sort

  • 1A searching algorithm requires at most 100n3log(n) + 25n^5 comparisons to search an array of n elements. The worst-case time complexity for the algorithm is

    O(n^3)O(n^5)O(n^3log(n))O(n^8)

  • Assume that Algorithm Test has a time complexity O(n^3), and that Algorithm Compute has time complexity O(n^2). What is the time complexity of the following algorithm?

    Execute Algorithm TestFor 5 trials, execute Algorithm ComputeExecute Algorithm Test

    O(n^3)O(n^2)O(n^18)O(n^16)

  • Which of the following statements about the standard binary search is valid?A non-recursive implementation of binary search requires a single loop containing a conditional statement.Insertion of a new element requires one step, a single array access, not a loop.Deleting one element requires one step, an array access, not a loop.In a search for one element X which is not in the array, every element in the array is accessed to determine if it equals X.

  • What does the following code fragment do? (All variables are of type int.)

    position1 = -1; position2 = -1; for (j = 0; j < 50; j++) for (i = 0; i < 50; i++) if (arr[i][j] == searchValue) { position1 = i; position2 = j; }It searches the array in row order for the first occurrence of searchValueIt searches the array in row order for the last occurrence of searchValueIt searches the array in column order for the first occurrence of searchValueIt searches the array in column order for the last occurrence of searchValue

  • Part 3: Linked List

  • 1Let the following struct be used to create linked lists:struct listnode { int data; listnode* next;};Let p point to the head of an existing linked list with more than one element. The following code segment is supposed insert the node pointed to by q at the end of the linked list pointed to by p?

    listnode* temp;temp = p;while (**A**) **B**;temp->next = q;What line of code should replace **B**?

    p = p->next;

    temp++;

    temp = temp.next;

    temp = temp ->next;

  • 2If there is a NodePtr named toDelete whose value points to a valid node in the list, which of the following statements would remove the node that follows toDelete from the list and return that memory to the freestore?

    tmp = toDelete -> link;toDelete -> link = toDelete->link->link;delete tmp;tmp = toDelete -> link;toDelete -> link = tmp -> link;delete tmp;tmp = toDelete->link->link;toDelete -> link = toDelete->link->link;delete tmp;All of the others answers;

  • 3Which of the following statements is not true?Singly linked lists can increase their sizes faster than arrays can increase their sizesThe singly-linked list does not allow you to access the nth element in constant timeYou can search for and find a value in an array in constant time.If you mistakingly mis-assign the head pointer to NULL, you will lose the entire list

  • 4Suppose a Deque is implemented by a singly linked list with a reference to the first node and a reference to the last node. Which of the following operations take O(n) time?Add a new member at the beginning of a Deque.Add a new member at the end of a Deque.Remove a member from the beginning of a Deque.Remove a member from the end of a Deque.

  • Part 4: BST

  • We say "postorder traversal of a tree" when we visit a nodeafter we visit all its childrennone of the othersbefore we visit all its childrenin the middle of visiting all its children

  • If I insert the integers 1 through n, in increasing order, into an initially empty Binary Search Tree, what is the height of the tree?O(n^1/2)O(n * log n)O(n)O(log n)

  • Consider this binary search tree in picture.

    Suppose we remove the root, replacing it with something from the left subtree. What will be the new root? 5674

  • What is the minimum height of a binary tree with 31 nodes?31567

  • Suppose T is a binary tree with 300 nodes. Which one of the following is the best estimation of the height of T?The height of T is at least 8;The height of T is at most 8;The height of T is at least 9.The height of T is at most 9;

  • If the inorder traversal of the binary tree T is

    A D B G C F E

    and each node of T has either 0 or 2 children, which of the following nodes is NOT a leaf of that tree?

    ABCD

  • What is the maximum height of a binary tree with 31 nodes?31567

  • Which of the following arrangements of general-purpose data structures is from slowest to fastest for the purpose of finding objects according to a key value: sorted arrays, unsorted linked lists, binary search treessorted arrays, binary search trees, linked lists

    binary search trees, unsorted arrays, sorted linked listssorted linked lists, sorted arrays, binary search trees

  • Which of the following arrangements of general-purpose data structures is from slowest to fastest for the purpose of storing objects by key value (not necessarily in order): unsorted arrays, sorted linked lists, binary search treessorted arrays, binary search trees, linked listsbinary search trees, sorted arrays, sorted linked listsunsorted arrays, linked lists, binary search trees

  • *#include #include #include

    void main(){int a,b,c;couta>>b>>c;int max=a;if (b>max) max=b;if (c>max) max=c;coutmax) max=c;printf("max= %d",max);}*#include #include #include void nhap(int a[][5],int m,int n);void xuat(int a[][5],int m,int n);void duyet(int a[][5],int m,int n,int x,int y);int count (int a[][5],int m,int n,int x,int y);//=======================main ===================================

    void main(){//randomize();int a[5][5];nhap (a,5,5);xuat(a,5,5);couty;cout