数据结构与算法分析-C语言(英文版)
c语言教程英文版讲义(一)
2Some Informationo Lecturingn C/C++ Language n Artificial Intelligence n Specialized Englisho Phone numbers and emailn Office: A0816n Phone: 84706003-3816n Email: eecc2012@3Textbooko 书名:C 语言教程(英文版·第4版)o 原书名:A Book on C:Programming in Co 作者:(美)Al Kelley, Ira Pohl o 出版社:China Machine Pres s4Professor of Computer and Information Scienceso Ira Pohl is a Professor of ComputerScience at the University of California, Santa Cruz.o His current research is in object-orientedprogramming(OOP) and topics in software methodology. He has written widely on programming in C, C++,C# and Java.o His research interests include artificialintelligence (AI), the C#, C, C++ and Java programming languages, practical complexity problems, heuristic search methods, etc..5Reference Readingo 书名:C 语言的科学和艺术(英文版)o 原书名:The Art andScience of C:A Library Based Introduction to Computer Science o 作者:Eric S.Robertso 出版社:China Machine Pres s6Reference Readingo 书名:C 程序设计语言(第2版·新版)o 原书名:The C ProgrammingLanguageo 作者:(美)Brian W.Kernighan,Dennis M.Ritchieo 出版社: Prentice-HallInternational , Inc.7Course administrationo Class hours :72 Credits :4n Teaching hours :48 hours (3 credits)n Practice hours :24 hours (1 credits)o Grading system :100n Final exam: 60%n Homework and Quizz: 15%n Projects: 25%Course administrationo Class is 4hours of lecture a week, Monday andWednesday at 13:30pm and 8:00amo 4 hours of practice a week ,6 weeks from 6th~11th week o 8hours a week of outside-the-class.9Why do we learn C language?o Today is the era of java and .net.oC is the fundament of OS. The kernel of Unix, Linux and Windows are written by C. Windows API is the interface of C functions. Unix/Linux applications are developed by C.oIf you want to be the superior of programmer, you must learn C language.oC# derived from C/C++What skills will you acquire?o You’re going to be able to write.o You’re going to be able to read.o Understand abilities and limits.o Understand what you can and cannot do.11How to study C programming:Some proverbso Standardization of formatn Well begun, half done.n A year ’s plan starts spring.o Have patiencen A workman must first sharpen his tools if he is to dohis work well.n Right tool for the right job.o Debug routinen Everything has a hard beginning.n Practice makes perfect.To follow, without halt, one aim:there the secret of success.12How to study C programming:o 1. Read all assigned reading in the textbook.--Not just once.--one paragraph at a time.--close the book, summarize the paragraph you just read.--If you could not summarize it quickly and accurately,read it again .o 2. Read your lecture notes in the same way.Type in all the programs you saw in class and make sure you understand them.o 3. Read the documentation of strcpy , strcat , strcmp ,malloc , calloc , strlen , printf , sprint , sscanf etc. Know how to find the documentation of any C library function and what is meant by "the documentation".o 4. Read your homework and make sure you know how itworks. The exams will definitely include several questions about the homework programs.13What I expect from you as a student:o Show up for classo Show up for class on timeo Know what the topic is for that dayo Have already read the corresponding part of the textbook (see the lecture schedule)o After the class meets, go over the material again (textbook, and notes, if any)o Do your homework (and on time!)o Do your own homework by yourself . (You can discuss it orally but you must do your own writing.)o Arrange your schedule so that you have identifiable hours each week to spend on this course.oWork at a steady pace throughout the semester instead of in frantic bursts just before the final exam.14What will we learn?o Program o Functionsn Declarationso Constant o Variablen fundamental :int, char, float, double n structured: array, struct, union n pointern Statementso assignmento control: if, for, do, while,…o compound o null150 Starting from Zero2 Lexical Element,Operators, and C System 3The Fundamental Data Types 4Flow of Control 5Functions6Arrays, Pointers and Strings7Bitwise Operators and Enumeration Types 8The preprocessor 9Structures and Unions 10Structures and List Processing11Input/Output and the Operating System13 Moving from C to C++Contents 16o Some termsn Computer language n Programn Programming n Algorithmo Program ’s Constitutionn Some representation of fundamental data n Give instructions to computer(decription of recipe)C/C++ Language17o What is the program?n data structure+algorithm=program n data structure+algorithm+structured programming method+language tool= programo Three basic structuresn Sequential n conditional n IterationC/C++LanguageNikiklaus Wirth——Computer Scientist18o 0.1 C ’s background o 0.2 C ’s Characteristic o 0.3 ANSI C Standard o 0.4 From C to C++o 0.5 From C and C++ to Java0 Starting from Zero19The basic organization of a computer system0.1 C ’s background Arithmetic sectionStorage sectionControl section Input device Output deviceresultprogramdataCPU20Machine languagesAssembly languagesHigh-level languageProcedure -oriented Object-oriented0.1 C ’s backgroundThe development of programming languages211.In the mid-1970s,UNIX spread throughout BellLabs.2.By 1980,several C compilers were put forward onthe market.3.By now,there are many versions of C languages.0.1 C ’s background The origin of C language 22True dialogueArtificial intelligence “ dialogues”Command languages(as in OS)Problem-oriented languages(Fortran, Pascal)Machine-oriented languages(BCPL,B)Assembly languagesHardware0.1 C ’s backgroundThe place of the C languageþýüþýülow-levelHigh-levelconcrete abstractdetailedgeneralpastfuture C23Algol60 (1960,an international committee)CPL (1963,Cambridge & Univ.of London)BCPL (1967, Martin Richards)B (1970, Ken Thompson)C (1972, Dennis Ritchie)0.1 C ’s background The development of the C language240.2 C ’s characteristicp C is a small language Keyword p C is the native language of Unix p C is portable Pascal p C is terse Operator p C is modularp C is the basis for C++ and Java p C is efficient on most machinesp C is not without criticism0.3 ANSI C Standard 26p C often serves as the kernel for more advanced or morespecialized languages.p C++ is an object-oriented language,it is the extension of C.0.4 From C to C++27p Java was designed for work on the Internetp It allows the programmer to write secure and portableprograms that can be downloaded from the Internet and run on your local machine.p Java borrows ideas from both C and C++ and is designed to run in a machine-and system-independent manner.0.5 From C and C++ to Java 28o Operating system o Source file o Text editor o Compiler o Object codeProgramming and preparation29We must do: 1. Edit it (*.c)2. Compile it (*.obj)3. Run it (*.exe)It depends on the system we are using.Programming and preparation 30Programming and preparation31VC++6.0Programming and preparation32“File ”→“New ”33“Files ”→“C++ Source Files ”34“File ”→“Save ”35“Build ”→“Compile test1.c ”36“Build ”→“Build test1.exe ”37“Build ”→“Execute test1.exe ”3839sea1.c#include <stdio.h>int main (){printf(“from sea to shining C\n ”);return 0;}Examplesfrom sea to shining CLibrary function 40sea2.c#include <stdio.h>void main(){printf(“from sea to ”);printf( “shining C ”);printf(“\n ”);}Examplesfrom sea to shining C41sea3.c#include <stdio.h>void main(){printf(“from sea\n ”);printf( “to shining \nC\n ”);}Examplesfrom sea to shining C42******************* from sea ** to shining C *******************43sea4.co #include <stdio.h>o void main()o {o printf("\n\n\n\n\n\n\n\n\n\n");o printf(" ******************\n");o printf(“* from sea *\n");o printf(“* to shining C *\n");o printf(" ******************\n");o printf("\n\n\n\n\n\n\n\n\n\n");o}Examples 44n miles and yards, kilometers. n Convert yards to miles, divide by 1760.0n Convert miles to kilometers, conversion factor 1.609n miles=yards/1760.0;nkilometers=1.609*miles;ExamplesIn English units, a marathon is defined to be2638542.245/* marathon .c The distance of a marathon in kilometers.*/Examples#include <stdio.h>void main(){ int miles,yards;float kilometers;miles=26;yards=385;kilometers=1.609*(miles+yards/1760.0);printf(“\nA marathon is %f kilometers.\n\n”, kilometers);}A marathon is 42.185969 kilometers.46/*The distance of a marathon in kilometers.*/Examplesp Convert the distance of a marathon in miles and yards to kilometers p int ,floatp V ariables must be declared at the beginning of the program p Identifier consists of a sequence of letters,digits,andunderscores,but may not start with a digit.p Comment p Semicolonp Assignment statement p precedence47Homeworko Write an interactive program that converts pounds andounces to kilograms and e symbolic constants that are defined at the top of the file outside of main().o 2. For a three-figure integer, get its unit's place , ten ’splace and hundred's place figure.o pute the roots of quadratic equation :ax 2+bx+c=0o 4.Input the three edges of a triangle, compute its area.o 5. Compute the BODY MASS INDEX(BMI)t= weight (kg)/height (m x m)ïïïîïïïíì³<£<£<£<II 0Obese .30 I 9Obese .9252t9Overweigh .42329Normal .225.18ht 5Underweig .18t t t t t 48Thank you!49Keywords( standard C:32)auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef unsigned union void volatile while50Keywords(C++:32)bad_cast bad_typeid bool catch classconst_cast delete dynameic_cast except explicitfinally friend inline mutable namespace new operator private protected public reinterpret-cast static_cast template this throwtrue try type-info typeid typename using virtual<51Control statements(9)if( )~else~for( )~while( )~do~while( )continue break switch goto return<52C & PascalC Pascal{ } BEGIN….END if(e) s; IF(e) THEN sint i ; VAR i:INTEGERint a[10]; VAR a:ARRAY[1..10] OF INTEGER int f(); FUNCTION f():INTEGERint *p;VAR p:-INTEGER<53Operatorsarithemetic:+ -* / % ++ --relational:< <= == > >= !=logical:!&& ||bitwise:<< >> ~ | ^ &assignment:= += -= *= /= %= &= ^= |= <<= >>=conditional:?:comma:,pointer:* &Bit count:sizeof case:(type-name)member:. ->index:[]others:( ) -<54Data TypesData typestandardstructure d pointer voidtypedefnumericchar enumintegral realfloatdoubleshort long intarraystruct union <55portableif (x>0) then BEGIN A:=1;B:= 2END;#define THEN #define BEGIN {#define := =#define END ; ;}if (x>0) {A=1;B=2;}<。
数据结构与算法分析C语言英文版
typedef struct list_node *list_ptr; typedef struct list_node {
char data [ 4 ] ;
N1->next = N2 ; N2->next = NULL ; ptr = N1 ;
list_ptr next ;
}; list_ptr ptr ;
array+i array+i+1
……
itemi itemi+1 ……
MaxSize has to be estimated.
Find_Kth takes O(1) time.
Insertion and Deletion not
only take O(N) time, but also involve a lot of data movements which takes time.
2. Linked Lists
Address
0010 0011 0110 1011
Data
SUN QIAN ZHAO
LI
Pointer
《数据结构与算法分析》(C++第二版)【美】Clifford A.Shaffer著 课后习题答案 二
《数据结构与算法分析》(C++第二版)【美】Clifford A.Shaffer著课后习题答案二5Binary Trees5.1 Consider a non-full binary tree. By definition, this tree must have some internalnode X with only one non-empty child. If we modify the tree to removeX, replacing it with its child, the modified tree will have a higher fraction ofnon-empty nodes since one non-empty node and one empty node have been removed.5.2 Use as the base case the tree of one leaf node. The number of degree-2 nodesis 0, and the number of leaves is 1. Thus, the theorem holds.For the induction hypothesis, assume the theorem is true for any tree withn − 1 nodes.For the induction step, consider a tree T with n nodes. Remove from the treeany leaf node, and call the resulting tree T. By the induction hypothesis, Thas one more leaf node than it has nodes of degree 2.Now, restore the leaf node that was removed to form T. There are twopossible cases.(1) If this leaf node is the only child of its parent in T, then the number ofnodes of degree 2 has not changed, nor has the number of leaf nodes. Thus,the theorem holds.(2) If this leaf node is the child of a node in T with degree 2, then that nodehas degree 1 in T. Thus, by restoring the leaf node we are adding one newleaf node and one new node of degree 2. Thus, the theorem holds.By mathematical induction, the theorem is correct.32335.3 Base Case: For the tree of one leaf node, I = 0, E = 0, n = 0, so thetheorem holds.Induction Hypothesis: The theorem holds for the full binary tree containingn internal nodes.Induction Step: Take an arbitrary tree (call it T) of n internal nodes. Selectsome internal node x from T that has two leaves, and remove those twoleaves. Call the resulting tree T’. Tree T’ is full and has n−1 internal nodes,so by the Induction Hypothesis E = I + 2(n − 1).Call the depth of node x as d. Restore the two children of x, each at leveld+1. We have nowadded d to I since x is now once again an internal node.We have now added 2(d + 1) − d = d + 2 to E since we added the two leafnodes, but lost the contribution of x to E. Thus, if before the addition we had E = I + 2(n − 1) (by the induction hypothesis), then after the addition we have E + d = I + d + 2 + 2(n − 1) or E = I + 2n which is correct. Thus,by the principle of mathematical induction, the theorem is correct.5.4 (a) template <class Elem>void inorder(BinNode<Elem>* subroot) {if (subroot == NULL) return; // Empty, do nothingpreorder(subroot->left());visit(subroot); // Perform desired actionpreorder(subroot->right());}(b) template <class Elem>void postorder(BinNode<Elem>* subroot) {if (subroot == NULL) return; // Empty, do nothingpreorder(subroot->left());preorder(subroot->right());visit(subroot); // Perform desired action}5.5 The key is to search both subtrees, as necessary.template <class Key, class Elem, class KEComp>bool search(BinNode<Elem>* subroot, Key K);if (subroot == NULL) return false;if (subroot->value() == K) return true;if (search(subroot->right())) return true;return search(subroot->left());}34 Chap. 5 Binary Trees5.6 The key is to use a queue to store subtrees to be processed.template <class Elem>void level(BinNode<Elem>* subroot) {AQueue<BinNode<Elem>*> Q;Q.enqueue(subroot);while(!Q.isEmpty()) {BinNode<Elem>* temp;Q.dequeue(temp);if(temp != NULL) {Print(temp);Q.enqueue(temp->left());Q.enqueue(temp->right());}}}5.7 template <class Elem>int height(BinNode<Elem>* subroot) {if (subroot == NULL) return 0; // Empty subtreereturn 1 + max(height(subroot->left()),height(subroot->right()));}5.8 template <class Elem>int count(BinNode<Elem>* subroot) {if (subroot == NULL) return 0; // Empty subtreeif (subroot->isLeaf()) return 1; // A leafreturn 1 + count(subroot->left()) +count(subroot->right());}5.9 (a) Since every node stores 4 bytes of data and 12 bytes of pointers, the overhead fraction is 12/16 = 75%.(b) Since every node stores 16 bytes of data and 8 bytes of pointers, the overhead fraction is 8/24 ≈ 33%.(c) Leaf nodes store 8 bytes of data and 4 bytes of pointers; internal nodesstore 8 bytes of data and 12 bytes of pointers. Since the nodes havedifferent sizes, the total space needed for internal nodes is not the sameas for leaf nodes. Students must be careful to do the calculation correctly,taking the weighting into account. The correct formula looks asfollows, given that there are x internal nodes and x leaf nodes.4x + 12x12x + 20x= 16/32 = 50%.(d) Leaf nodes store 4 bytes of data; internal nodes store 4 bytes of pointers. The formula looks as follows, given that there are x internal nodes and35x leaf nodes:4x4x + 4x= 4/8 = 50%.5.10 If equal valued nodes were allowed to appear in either subtree, then during a search for all nodes of a given value, whenever we encounter a node of that value the search would be required to search in both directions.5.11 This tree is identical to the tree of Figure 5.20(a), except that a node with value 5 will be added as the right child of the node with value 2.5.12 This tree is identical to the tree of Figure 5.20(b), except that the value 24 replaces the value 7, and the leaf node that originally contained 24 is removed from the tree.5.13 template <class Key, class Elem, class KEComp>int smallcount(BinNode<Elem>* root, Key K);if (root == NULL) return 0;if (KEComp.gt(root->value(), K))return smallcount(root->leftchild(), K);elsereturn smallcount(root->leftchild(), K) +smallcount(root->rightchild(), K) + 1;5.14 template <class Key, class Elem, class KEComp>void printRange(BinNode<Elem>* root, int low,int high) {if (root == NULL) return;if (KEComp.lt(high, root->val()) // all to leftprintRange(root->left(), low, high);else if (KEComp.gt(low, root->val())) // all to rightprintRange(root->right(), low, high);else { // Must process both childrenprintRange(root->left(), low, high);PRINT(root->value());printRange(root->right(), low, high);}}5.15 The minimum number of elements is contained in the heap with a single node at depth h − 1, for a total of 2h−1 nodes.The maximum number of elements is contained in the heap that has completely filled up level h − 1, for a total of 2h − 1 nodes.5.16 The largest element could be at any leaf node.5.17 The corresponding array will be in the following order (equivalent to level order for the heap):12 9 10 5 4 1 8 7 3 236 Chap. 5 Binary Trees5.18 (a) The array will take on the following order:6 5 3 4 2 1The value 7 will be at the end of the array.(b) The array will take on the following order:7 4 6 3 2 1The value 5 will be at the end of the array.5.19 // Min-heap classtemplate <class Elem, class Comp> class minheap {private:Elem* Heap; // Pointer to the heap arrayint size; // Maximum size of the heapint n; // # of elements now in the heapvoid siftdown(int); // Put element in correct placepublic:minheap(Elem* h, int num, int max) // Constructor{ Heap = h; n = num; size = max; buildHeap(); }int heapsize() const // Return current size{ return n; }bool isLeaf(int pos) const // TRUE if pos a leaf{ return (pos >= n/2) && (pos < n); }int leftchild(int pos) const{ return 2*pos + 1; } // Return leftchild posint rightchild(int pos) const{ return 2*pos + 2; } // Return rightchild posint parent(int pos) const // Return parent position { return (pos-1)/2; }bool insert(const Elem&); // Insert value into heap bool removemin(Elem&); // Remove maximum value bool remove(int, Elem&); // Remove from given pos void buildHeap() // Heapify contents{ for (int i=n/2-1; i>=0; i--) siftdown(i); }};template <class Elem, class Comp>void minheap<Elem, Comp>::siftdown(int pos) { while (!isLeaf(pos)) { // Stop if pos is a leafint j = leftchild(pos); int rc = rightchild(pos);if ((rc < n) && Comp::gt(Heap[j], Heap[rc]))j = rc; // Set j to lesser child’s valueif (!Comp::gt(Heap[pos], Heap[j])) return; // Done37swap(Heap, pos, j);pos = j; // Move down}}template <class Elem, class Comp>bool minheap<Elem, Comp>::insert(const Elem& val) { if (n >= size) return false; // Heap is fullint curr = n++;Heap[curr] = val; // Start at end of heap// Now sift up until curr’s parent < currwhile ((curr!=0) &&(Comp::lt(Heap[curr], Heap[parent(curr)]))) {swap(Heap, curr, parent(curr));curr = parent(curr);}return true;}template <class Elem, class Comp>bool minheap<Elem, Comp>::removemin(Elem& it) { if (n == 0) return false; // Heap is emptyswap(Heap, 0, --n); // Swap max with last valueif (n != 0) siftdown(0); // Siftdown new root valit = Heap[n]; // Return deleted valuereturn true;}38 Chap. 5 Binary Trees// Remove value at specified positiontemplate <class Elem, class Comp>bool minheap<Elem, Comp>::remove(int pos, Elem& it) {if ((pos < 0) || (pos >= n)) return false; // Bad posswap(Heap, pos, --n); // Swap with last valuewhile ((pos != 0) &&(Comp::lt(Heap[pos], Heap[parent(pos)])))swap(Heap, pos, parent(pos)); // Push up if largesiftdown(pos); // Push down if small keyit = Heap[n];return true;}5.20 Note that this summation is similar to Equation 2.5. To solve the summation requires the shifting technique from Chapter 14, so this problem may be too advanced for many students at this time. Note that 2f(n) − f(n) = f(n),but also that:2f(n) − f(n) = n(24+48+616+ ··· +2(log n − 1)n) −n(14+28+316+ ··· +log n − 1n)logn−1i=112i− log n − 1n)= n(1 − 1n− log n − 1n)= n − log n.5.21 Here are the final codes, rather than a picture.l 00h 010i 011e 1000f 1001j 101d 11000a 1100100b 1100101c 110011g 1101k 11139The average code length is 3.234455.22 The set of sixteen characters with equal weight will create a Huffman coding tree that is complete with 16 leaf nodes all at depth 4. Thus, the average code length will be 4 bits. This is identical to the fixed length code. Thus, in this situation, the Huffman coding tree saves no space (and costs no space).5.23 (a) By the prefix property, there can be no character with codes 0, 00, or 001x where “x” stands for any binary string.(b) There must be at least one code with each form 1x, 01x, 000x where“x” could be any binary string (including the empty string).5.24 (a) Q and Z are at level 5, so any string of length n containing only Q’s and Z’s requires 5n bits.(b) O and E are at level 2, so any string of length n containing only O’s and E’s requires 2n bits.(c) The weighted average is5 ∗ 5 + 10 ∗ 4 + 35 ∗ 3 + 50 ∗ 2100bits per character5.25 This is a straightforward modification.// Build a Huffman tree from minheap h1template <class Elem>HuffTree<Elem>*buildHuff(minheap<HuffTree<Elem>*,HHCompare<Elem> >* hl) {HuffTree<Elem> *temp1, *temp2, *temp3;while(h1->heapsize() > 1) { // While at least 2 itemshl->removemin(temp1); // Pull first two treeshl->removemin(temp2); // off the heaptemp3 = new HuffTree<Elem>(temp1, temp2);hl->insert(temp3); // Put the new tree back on listdelete temp1; // Must delete the remnantsdelete temp2; // of the trees we created}return temp3;}6General Trees6.1 The following algorithm is linear on the size of the two trees. // Return TRUE iff t1 and t2 are roots of identical// general treestemplate <class Elem>bool Compare(GTNode<Elem>* t1, GTNode<Elem>* t2) { GTNode<Elem> *c1, *c2;if (((t1 == NULL) && (t2 != NULL)) ||((t2 == NULL) && (t1 != NULL)))return false;if ((t1 == NULL) && (t2 == NULL)) return true;if (t1->val() != t2->val()) return false;c1 = t1->leftmost_child();c2 = t2->leftmost_child();while(!((c1 == NULL) && (c2 == NULL))) {if (!Compare(c1, c2)) return false;if (c1 != NULL) c1 = c1->right_sibling();if (c2 != NULL) c2 = c2->right_sibling();}}6.2 The following algorithm is Θ(n2).// Return true iff t1 and t2 are roots of identical// binary treestemplate <class Elem>bool Compare2(BinNode<Elem>* t1, BinNode<Elem* t2) { BinNode<Elem> *c1, *c2;if (((t1 == NULL) && (t2 != NULL)) ||((t2 == NULL) && (t1 != NULL)))return false;if ((t1 == NULL) && (t2 == NULL)) return true;4041if (t1->val() != t2->val()) return false;if (Compare2(t1->leftchild(), t2->leftchild())if (Compare2(t1->rightchild(), t2->rightchild())return true;if (Compare2(t1->leftchild(), t2->rightchild())if (Compare2(t1->rightchild(), t2->leftchild))return true;return false;}6.3 template <class Elem> // Print, postorder traversalvoid postprint(GTNode<Elem>* subroot) {for (GTNode<Elem>* temp = subroot->leftmost_child();temp != NULL; temp = temp->right_sibling())postprint(temp);if (subroot->isLeaf()) cout << "Leaf: ";else cout << "Internal: ";cout << subroot->value() << "\n";}6.4 template <class Elem> // Count the number of nodesint gencount(GTNode<Elem>* subroot) {if (subroot == NULL) return 0int count = 1;GTNode<Elem>* temp = rt->leftmost_child();while (temp != NULL) {count += gencount(temp);temp = temp->right_sibling();}return count;}6.5 The Weighted Union Rule requires that when two parent-pointer trees are merged, the smaller one’s root becomes a child of the larger one’s root. Thus, we need to keep track of the number of nodes in a tree. To do so, modify the node array to store an integer value with each node. Initially, each node isin its own tree, so the weights for each node begin as 1. Whenever we wishto merge two trees, check the weights of the roots to determine which has more nodes. Then, add to the weight of the final root the weight of the new subtree.6.60 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15-1 0 0 0 0 0 0 6 0 0 0 9 0 0 12 06.7 The resulting tree should have the following structure:42 Chap. 6 General TreesNode 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15Parent 4 4 4 4 -1 4 4 0 0 4 9 9 9 12 9 -16.8 For eight nodes labeled 0 through 7, use the following series of equivalences: (0, 1) (2, 3) (4, 5) (6, 7) (4 6) (0, 2) (4 0)This requires checking fourteen parent pointers (two for each equivalence),but none are actually followed since these are all roots. It is possible todouble the number of parent pointers checked by choosing direct children ofroots in each case.6.9 For the “lists of Children” representation, every node stores a data value and a pointer to its list of children. Further, every child (every node except the root)has a record associated with it containing an index and a pointer. Indicatingthe size of the data value as D, the size of a pointer as P and the size of anindex as I, the overhead fraction is3P + ID + 3P + I.For the “Left Child/Right Sibling” representation, every node stores three pointers and a data value, for an overhead fraction of3PD + 3P.The first linked representation of Section 6.3.3 stores with each node a datavalue and a size field (denoted by S). Each child (every node except the root)also has a pointer pointing to it. The overhead fraction is thusS + PD + S + Pmaking it quite efficient.The second linked representation of Section 6.3.3 stores with each node adata value and a pointer to the list of children. Each child (every node exceptthe root) has two additional pointers associated with it to indicate its placeon the parent’s linked list. Thus, the overhead fraction is3PD + 3P.6.10 template <class Elem>BinNode<Elem>* convert(GTNode<Elem>* genroot) {if (genroot == NULL) return NULL;43GTNode<Elem>* gtemp = genroot->leftmost_child();btemp = new BinNode(genroot->val(), convert(gtemp),convert(genroot->right_sibling()));}6.11 • Parent(r) = (r − 1)/k if 0 < r < n.• Ith child(r) = kr + I if kr +I < n.• Left sibling(r) = r − 1 if r mod k = 1 0 < r < n.• Right sibling(r) = r + 1 if r mod k = 0 and r + 1 < n.6.12 (a) The overhead fraction is4(k + 1)4 + 4(k + 1).(b) The overhead fraction is4k16 + 4k.(c) The overhead fraction is4(k + 2)16 + 4(k + 2).(d) The overhead fraction is2k2k + 4.6.13 Base Case: The number of leaves in a non-empty tree of 0 internal nodes is (K − 1)0 + 1 = 1. Thus, the theorem is correct in the base case.Induction Hypothesis: Assume that the theorem is correct for any full Karytree containing n internal nodes.Induction Step: Add K children to an arbitrary leaf node of the tree withn internal nodes. This new tree now has 1 more internal node, and K − 1more leaf nodes, so theorem still holds. Thus, the theorem is correct, by the principle of Mathematical Induction.6.14 (a) CA/BG///FEDD///H/I//(b) CA/BG/FED/H/I6.15 X|P-----| | |C Q R---| |V M44 Chap. 6 General Trees6.16 (a) // Use a helper function with a pass-by-reference// variable to indicate current position in the// node list.template <class Elem>BinNode<Elem>* convert(char* inlist) {int curr = 0;return converthelp(inlist, curr);}// As converthelp processes the node list, curr is// incremented appropriately.template <class Elem>BinNode<Elem>* converthelp(char* inlist,int& curr) {if (inlist[curr] == ’/’) {curr++;return NULL;}BinNode<Elem>* temp = new BinNode(inlist[curr++], NULL, NULL);temp->left = converthelp(inlist, curr);temp->right = converthelp(inlist, curr);return temp;}(b) // Use a helper function with a pass-by-reference // variable to indicate current position in the// node list.template <class Elem>BinNode<Elem>* convert(char* inlist) {int curr = 0;return converthelp(inlist, curr);}// As converthelp processes the node list, curr is// incremented appropriately.template <class Elem>BinNode<Elem>* converthelp(char* inlist,int& curr) {if (inlist[curr] == ’/’) {curr++;return NULL;}BinNode<Elem>* temp =new BinNode<Elem>(inlist[curr++], NULL, NULL);if (inlist[curr] == ’\’’) return temp;45curr++ // Eat the internal node mark.temp->left = converthelp(inlist, curr);temp->right = converthelp(inlist, curr);return temp;}(c) // Use a helper function with a pass-by-reference// variable to indicate current position in the// node list.template <class Elem>GTNode<Elem>* convert(char* inlist) {int curr = 0;return converthelp(inlist, curr);}// As converthelp processes the node list, curr is// incremented appropriately.template <class Elem>GTNode<Elem>* converthelp(char* inlist,int& curr) {if (inlist[curr] == ’)’) {curr++;return NULL;}GTNode<Elem>* temp =new GTNode<Elem>(inlist[curr++]);if (curr == ’)’) {temp->insert_first(NULL);return temp;}temp->insert_first(converthelp(inlist, curr));while (curr != ’)’)temp->insert_next(converthelp(inlist, curr));curr++;return temp;}6.17 The Huffman tree is a full binary tree. To decode, we do not need to know the weights of nodes, only the letter values stored in the leaf nodes. Thus, we can use a coding much like that of Equation 6.2, storing only a bit mark for internal nodes, and a bit mark and letter value for leaf nodes.7Internal Sorting7.1 Base Case: For the list of one element, the double loop is not executed and the list is not processed. Thus, the list of one element remains unaltered and is sorted.Induction Hypothesis: Assume that the list of n elements is sorted correctlyby Insertion Sort.Induction Step: The list of n + 1 elements is processed by first sorting thetop n elements. By the induction hypothesis, this is done correctly. The final pass of the outer for loop will process the last element (call it X). This isdone by the inner for loop, which moves X up the list until a value smallerthan that of X is encountered. At this point, X has been properly insertedinto the sorted list, leaving the entire collection of n + 1 elements correctly sorted. Thus, by the principle of Mathematical Induction, the theorem is correct.7.2 void StackSort(AStack<int>& IN) {AStack<int> Temp1, Temp2;while (!IN.isEmpty()) // Transfer to another stackTemp1.push(IN.pop());IN.push(Temp1.pop()); // Put back one elementwhile (!Temp1.isEmpty()) { // Process rest of elemswhile (IN.top() > Temp1.top()) // Find elem’s placeTemp2.push(IN.pop());IN.push(Temp1.pop()); // Put the element inwhile (!Temp2.isEmpty()) // Put the rest backIN.push(Temp2.pop());}}46477.3 The revised algorithm will work correctly, and its asymptotic complexity will remain Θ(n2). However, it will do about twice as many comparisons, since it will compare adjacent elements within the portion of the list already knownto be sorted. These additional comparisons are unproductive.7.4 While binary search will find the proper place to locate the next element, it will still be necessary to move the intervening elements down one position in the array. This requires the same number of operations as a sequential search. However, it does reduce the number of element/element comparisons, and may be somewhat faster by a constant factor since shifting several elements may be more efficient than an equal number of swap operations.7.5 (a) template <class Elem, class Comp>void selsort(Elem A[], int n) { // Selection Sortfor (int i=0; i<n-1; i++) { // Select i’th recordint lowindex = i; // Remember its indexfor (int j=n-1; j>i; j--) // Find least valueif (Comp::lt(A[j], A[lowindex]))lowindex = j; // Put it in placeif (i != lowindex) // Add check for exerciseswap(A, i, lowindex);}}(b) There is unlikely to be much improvement; more likely the algorithmwill slow down. This is because the time spent checking (n times) isunlikely to save enough swaps to make up.(c) Try it and see!7.6 • Insertion Sort is stable. A swap is done only if the lower element’svalue is LESS.• Bubble Sort is stable. A swap is done only if the lower element’s valueis LESS.• Selection Sort is NOT stable. The new low value is set only if it isactually less than the previous one, but the direction of the search isfrom the bottom of the array. The algorithm will be stable if “less than”in the check becomes “less than or equal to” for selecting the low key position.• Shell Sort is NOT stable. The sublist sorts are done independently, andit is quite possible to swap an element in one sublist ahead of its equalvalue in another sublist. Once they are in the same sublist, they willretain this (incorrect) relationship.• Quick-sort is NOT stable. After selecting the pivot, it is swapped withthe last element. This action can easily put equal records out of place.48 Chap. 7 Internal Sorting• Conceptually (in particular, the linked list version) Mergesort is stable.The array implementations are NOT stable, since, given that the sublistsare stable, the merge operation will pick the element from the lower listbefore the upper list if they are equal. This is easily modified to replace“less than” with “less than or equal to.”• Heapsort is NOT stable. Elements in separate sides of the heap are processed independently, and could easily become out of relative order.• Binsort is stable. Equal values that come later are appended to the list.• Radix Sort is stable. While the processing is from bottom to top, thebins are also filled from bottom to top, preserving relative order.7.7 In the worst case, the stack can store n records. This can be cut to log n in the worst case by putting the larger partition on FIRST, followed by the smaller. Thus, the smaller will be processed first, cutting the size of the next stacked partition by at least half.7.8 Here is how I derived a permutation that will give the desired (worst-case) behavior:a b c 0 d e f g First, put 0 in pivot index (0+7/2),assign labels to the other positionsa b c g d e f 0 First swap0 b c g d e f a End of first partition pass0 b c g 1 e f a Set d = 1, it is in pivot index (1+7/2)0 b c g a e f 1 First swap0 1 c g a e f b End of partition pass0 1 c g 2 e f b Set a = 2, it is in pivot index (2+7/2)0 1 c g b e f 2 First swap0 1 2 g b e f c End of partition pass0 1 2 g b 3 f c Set e = 3, it is in pivot index (3+7/2)0 1 2 g b c f 3 First swap0 1 2 3 b c f g End of partition pass0 1 2 3 b 4 f g Set c = 4, it is in pivot index (4+7/2)0 1 2 3 b g f 4 First swap0 1 2 3 4 g f b End of partition pass0 1 2 3 4 g 5 b Set f = 5, it is in pivot index (5+7/2)0 1 2 3 4 g b 5 First swap0 1 2 3 4 5 b g End of partition pass0 1 2 3 4 5 6 g Set b = 6, it is in pivot index (6+7/2)0 1 2 3 4 5 g 6 First swap0 1 2 3 4 5 6 g End of parition pass0 1 2 3 4 5 6 7 Set g = 7.Plugging the variable assignments into the original permutation yields:492 6 4 0 13 5 77.9 (a) Each call to qsort costs Θ(i log i). Thus, the total cost isni=1i log i = Θ(n2 log n).(b) Each call to qsort costs Θ(n log n) for length(L) = n, so the totalcost is Θ(n2 log n).7.10 All that we need to do is redefine the comparison test to use strcmp. The quicksort algorithm itself need not change. This is the advantage of paramerizing the comparator.7.11 For n = 1000, n2 = 1, 000, 000, n1.5 = 1000 ∗√1000 ≈ 32, 000, andn log n ≈ 10, 000. So, the constant factor for Shellsort can be anything less than about 32 times that of Insertion Sort for Shellsort to be faster. The constant factor for Shellsort can be anything less than about 100 times thatof Insertion Sort for Quicksort to be faster.7.12 (a) The worst case occurs when all of the sublists are of size 1, except for one list of size i − k + 1. If this happens on each call to SPLITk, thenthe total cost of the algorithm will be Θ(n2).(b) In the average case, the lists are split into k sublists of roughly equal length. Thus, the total cost is Θ(n logk n).7.13 (This question comes from Rawlins.) Assume that all nuts and all bolts havea partner. We use two arrays N[1..n] and B[1..n] to represent nuts and bolts. Algorithm 1Using merge-sort to solve this problem.First, split the input into n/2 sub-lists such that each sub-list contains twonuts and two bolts. Then sort each sub-lists. We could well come up with apair of nuts that are both smaller than either of a pair of bolts. In that case,all you can know is something like:N1, N2。
数据结构与算法分析c语言描述
数据结构与算法分析c语言描述
《数据结构与算法分析》是一本经典的计算机科学书籍,由Mark Allen Weiss编写。
书中涵盖了基本的数据结构和算法,
以及它们之间的分析和比较。
其中包括数组、链表、栈、队列、树、哈希表、图等数据结构,以及排序、搜索、动态规划、回溯、贪婪算法等算法。
书中的代码主要是用C语言编写的,可以帮助读者更好地理
解和实现数据结构和算法。
比如,为了实现一个堆栈,可以使用C语言定义一个结构体,用来存储堆栈的元素,并定义一
系列函数来实现堆栈的基本操作,如入栈、出栈、获取栈顶元素等。
此外,书中还提供了一些实用的算法设计技巧,可以帮助读者更好地理解和实现算法。
比如,书中提供了一种分治算法的设计方法,可以帮助读者将一个复杂的问题分解成多个规模较小的问题,从而实现更高效的算法。
the c programming language 英文版
C语言圣经:C语言基础知识与高级应用《The C Programming Language》英文版是由Kernighan和Ritchie 合著的一本介绍C语言的经典教材。
该书于1978年首次出版,一经推出便成为学习C语言的必读教材之一。
该书共分为十章,涵盖了C语言的基本语法、数据类型、控制结构、函数、指针、文件和标准库等内容。
作者在书中详细解释了C语言的语法细节,并通过大量的例程和案例分析帮助读者更好地理解和掌握C语言编程。
此外,《The C Programming Language》还具有以下特点:
言简意赅:作者在书中使用了简洁明了的文字和代码示例来解释C语言的概念和语法,使得读者能够快速理解和掌握C语言编程。
案例丰富:书中提供了大量的例程和案例分析,这些案例涵盖了C语言的各种应用场景,包括数值计算、字符串处理、文件操作等,使得读者能够更好地理解和应用C语言编程。
强调实践:该书强调实践编程的重要性,鼓励读者自己动手编写程序并调试运行。
书中还提供了大量的编程练习和思考题,帮助读者巩固所学知识并提高编程能力。
适合初学者:该书从C语言的基本语法和语义开始讲解,逐步深入到高级主题,使得初学者能够逐步掌握C语言编程。
同时,书中还提供了许多实用的编程技巧和注意事项,帮助读者避免在编程过程中出现错误。
总之,《The C Programming Language》是一本非常优秀的C语言
教材,适合初学者和有一定经验的C语言开发者阅读。
通过阅读该书,读者可以快速掌握C语言编程的核心概念和技术,提高自己的编程能力和水平。
C语言英文版课件
Zhang Xiaohang
张晓航 zhxiaohang@
C Language Programming
2
Class
12B07 12B08 12B09 12B10
Theory (place & time)
教二楼326 13:30~15:20 Monday
– Electronic components – Human operator manipulated external wiring
• Electrical Numerical Integrator and Computer (ENIAC, 1946)
– 18,000 Vacuum tubes – Weighted 30 tons / 5000 additions or 360 multiplications
Textbook: A First Book of ANSI C Fourth Edition
Grade is determined by –Experiment 10%
–Middle exam 15%
–Course work 5% –Final exam 70%
Website: /CPF
• The collections of patterns consisting of 0s and 1s used to represent letters, single digits, and other single characters are called character codes(字符编码)
• Mark I (1944)
– Mechanical relay switches
• Electronic Delayed Storage Automatic Computer (EDSAC, 1949)
计算机专业必读技术书籍
【38】 “面向模式的软件体系结构 卷1:模式系统”( Pattern-Oriented Software Architecture, Volume 1: A System of Patterns)
漫长的三年过去了,我们摸爬滚打,没有指路的明灯。我也在摸索中走了不少的弯路,向我的软件班的同学引荐别人推荐几本好书(我也是在查漏补缺),希望有志者能少走些弯路。
一、 ቤተ መጻሕፍቲ ባይዱ学哲学和管理哲学
【1】 “程序开发心理学”(The Psychology of Computer Programming : Silver Anniversary Edition)
八、 软件维护和重构
【53】 “重构-改善既有代码的设计”(Refactoring: Improving the Design of Existing Code)
九、 配置管理和版本控制
【54】 “版本控制之道 —— 使用CVS”(程序员修炼三部曲第一部:Pragmatic Version Control Using CVS)
【21】 “人件集 —— 人性化的软件开发”( The Peopleware Papers: Notes on the Human Side of Software)
【22】 “人月神话”(The Mythical Man-Month)
【23】 “软件工程 — 实践者的研究方法(原书第5版)”(Software Engineering: A Practitioner's Approach, Fifth Edition)
c++ 信奥赛 常用英语
c++ 信奥赛常用英语在C++ 信奥赛中(计算机奥林匹克竞赛),常用英语词汇主要包括以下几方面:1. 基本概念:- Algorithm(算法)- Data structure(数据结构)- Programming language(编程语言)- C++(C++ 编程语言)- Object-oriented(面向对象)- Function(函数)- Variable(变量)- Constants(常量)- Loops(循环)- Conditional statements(条件语句)- Operators(运算符)- Control structures(控制结构)- Memory management(内存管理)2. 常用算法与数据结构:- Sorting algorithms(排序算法)- Searching algorithms(搜索算法)- Graph algorithms(图算法)- Tree algorithms(树算法)- Dynamic programming(动态规划)- Backtracking(回溯)- Brute force(暴力破解)- Divide and conquer(分治)- Greedy algorithms(贪心算法)- Integer array(整数数组)- Linked list(链表)- Stack(栈)- Queue(队列)- Tree(树)- Graph(图)3. 编程实践:- Code optimization(代码优化)- Debugging(调试)- Testing(测试)- Time complexity(时间复杂度)- Space complexity(空间复杂度)- Input/output(输入/输出)- File handling(文件处理)- Console output(控制台输出)4. 竞赛相关:- IOI(国际信息学奥林匹克竞赛)- NOI(全国信息学奥林匹克竞赛)- ACM-ICPC(ACM 国际大学生程序设计竞赛)- Codeforces(代码力)- LeetCode(力扣)- HackerRank(黑客排名)这些英语词汇在信奥赛领域具有广泛的应用,掌握这些词汇有助于提高选手之间的交流效率,同时对提升编程能力和竞赛成绩也有很大帮助。
数据结构与算法常用英语词汇
数据结构与算法常用英语词汇.txt 女人谨记:一定要吃好玩好睡好喝好。
一旦累死了,就别的女人花咱的钱,住咱的房,睡咱的老公,泡咱的男朋友,还打咱的娃。
第一部份计算机算法常用术语中英对照Data Structures 基本数据结构Dictionaries 字典Priority Queues 堆Graph Data Structures 图Set Data Structures 集合Kd-Trees 线段树Numerical Problems 数值问题Solving Linear Equations 线性方程组Bandwidth Reduction 带宽压缩Matrix Multiplication 矩阵乘法Determinants and Permanents 行列式Constrained and Unconstrained Optimization 最值问题Linear Programming 线性规划Random Number Generation 随机数生成Factoring and Primality Testing 因子分解/质数判定Arbitrary Precision Arithmetic 高精度计算Knapsack Problem 背包问题Discrete Fourier Transform 离散 Fourier 变换Combinatorial Problems 组合问题Sorting 排序Searching 查找Median and Selection 中位数Generating Permutations 罗列生成Generating Subsets 子集生成Generating Partitions 划分生成Generating Graphs 图的生成Calendrical Calculations 日期Job Scheduling 工程安排Satisfiability 可满足性Graph Problems -- polynomial 图论-多项式算法Connected Components 连通分支Topological Sorting 拓扑排序Minimum Spanning Tree 最小生成树Shortest Path 最短路径Transitive Closure and Reduction 传递闭包Matching 匹配Eulerian Cycle / Chinese Postman Euler 回路/中国邮路Edge and Vertex Connectivity 割边/割点Network Flow 网络流Drawing Graphs Nicely 图的描绘Drawing Trees 树的描绘Planarity Detection and Embedding 平面性检测和嵌入Graph Problems -- hard 图论-NP 问题Clique 最大团Independent Set 独立集Vertex Cover 点覆盖Traveling Salesman Problem 旅行商问题Hamiltonian Cycle Hamilton 回路Graph Partition 图的划分Vertex Coloring 点染色Edge Coloring 边染色Graph Isomorphism 同构Steiner Tree Steiner 树Feedback Edge/Vertex Set 最大无环子图Computational Geometry 计算几何Convex Hull 凸包Triangulation 三角剖分Voronoi Diagrams Voronoi 图Nearest Neighbor Search 最近点对查询Range Search 范围查询Point Location 位置查询Intersection Detection 碰撞测试Bin Packing 装箱问题Medial-Axis Transformation 中轴变换Polygon Partitioning 多边形分割Simplifying Polygons 多边形化简Shape Similarity 相似多边形Motion Planning 运动规划Maintaining Line Arrangements 平面分割Minkowski Sum Minkowski 和Set and String Problems 集合与串的问题Set Cover 集合覆盖Set Packing 集合配置String Matching 模式匹配Approximate String Matching 含糊匹配Text Compression 压缩Cryptography 密码Finite State Machine Minimization 有穷自动机简化Longest Common Substring 最长公共子串Shortest Common Superstring 最短公共父串DP——Dynamic Programming——动态规划recursion ——递归第二部份数据结构英语词汇数据抽象 data abstraction数据元素 data element数据对象 data object数据项 data item数据类型 data type抽象数据类型 abstract data type逻辑结构 logical structure物理结构 phyical structure线性结构 linear structure非线性结构 nonlinear structure基本数据类型 atomic data type固定聚合数据类型 fixed-aggregate data type可变聚合数据类型 variable-aggregate data type 线性表 linear list栈 stack队列 queue串 string数组 array树 tree图 grabh查找,线索 searching更新 updating排序(分类) sorting插入 insertion删除 deletion前趋 predecessor后继 successor直接前趋直接后继双端列表循环队列immediate predecessor immediate successor deque(double-ended queue) cirular queue指针 pointer先进先出表(队列) first-in first-out list 后进先出表(队列) last-in first-out list栈底栈定压入弹出队头bottom top push pop front队尾 rear上溢 overflow下溢 underflow数组 array矩阵 matrix多维数组 multi-dimentional array以行为主的顺序分配 row major order以列为主的顺序分配 column major order 三角矩阵 truangular matrix对称矩阵 symmetric matrix稀疏矩阵 sparse matrix转置矩阵 transposed matrix链表 linked list线性链表 linear linked list单链表 single linked list多重链表 multilinked list循环链表 circular linked list双向链表 doubly linked list十字链表 orthogonal list广义表 generalized list链 link指针域 pointer field链域 link field头结点 head 头指针 head 尾指针 tail 串 string node pointer pointer空白(空格)串blank string 空串(零串) null string子串 substring树 tree子树 subtree森林 forest根 root叶子结点深度层次双亲孩子leaf node depth level parents children兄弟 brother祖先 ancestor子孙 descentdant二叉树 binary tree平衡二叉树 banlanced binary tree 满二叉树 full binary tree彻底二叉树 complete binary tree遍历二叉树 traversing binary tree 二叉排序树 binary sort tree二叉查找树 binary search tree线索二叉树 threaded binary tree 哈夫曼树 Huffman tree有序数 ordered tree无序数 unordered tree判定树 decision tree双链树 doubly linked tree数字查找树 digital search tree树的遍历 traversal of tree先序遍历 preorder traversal中序遍历 inorder traversal后序遍历 postorder traversal图 graph子图 subgraph有向图无向图彻底图连通图digraph(directed graph) undigraph(undirected graph) complete graphconnected graph非连通图 unconnected graph强连通图 strongly connected graph 弱连通图 weakly connected graph 加权图 weighted graph有向无环图 directed acyclic graph 稀疏图 spares graph稠密图 dense graph重连通图 biconnected graph二部图 bipartite graph边 edge顶点 vertex弧 arc路径 path回路(环) cycle弧头弧尾源点终点汇点headtailsource destination sink权 weight连接点 articulation point 初始结点 initial node终端结点 terminal node相邻边 adjacent edge相邻顶点 adjacent vertex 关联边 incident edge入度 indegree出度 outdegree最短路径 shortest path有序对 ordered pair无序对 unordered pair简单路径简单回路连通分量邻接矩阵simple pathsimple cycle connected component adjacency matrix邻接表 adjacency list邻接多重表 adjacency multilist遍历图 traversing graph生成树 spanning tree最小(代价)生成树 minimum(cost)spanning tree生成森林 spanning forest拓扑排序 topological sort偏序 partical order拓扑有序 topological orderAOV 网 activity on vertex networkAOE 网 activity on edge network关键路径 critical path匹配 matching最大匹配 maximum matching增广路径 augmenting path增广路径图 augmenting path graph查找 searching线性查找(顺序查找) linear search (sequential search)二分查找 binary search分块查找 block search散列查找 hash search平均查找长度 average search length散列表 hash table散列函数 hash funticion直接定址法 immediately allocating method 数字分析法 digital analysis method平方取中法 mid-square method折叠法 folding method除法 division method随机数法 random number method排序 sort内部排序 internal sort外部排序 external sort插入排序 insertion sort随小增量排序 diminishing increment sort 选择排序 selection sort堆排序 heap sort快速排序归并排序基数排序外部排序quick sort merge sortradix sort external sort平衡归并排序 balance merging sort二路平衡归并排序 balance two-way merging sort 多步归并排序 ployphase merging sort置换选择排序 replacement selection sort文件 file主文件 master file顺叙文件 sequential file索引文件 indexed file索引顺叙文件 indexed sequential file索引非顺叙文件 indexed non-sequential file直接存取文件 direct access file多重链表文件 multilist file倒排文件 inverted file目录结构 directory structure树型索引 tree index。
数据结构例题(英文版)
I Single Choice(10 points)1. ( )For the following program fragment the running time(Big-Oh) is .i = 0;s = 0;while(s <( 5*n*n + 2)){ i++;s = s + i;}a. O(n)b. O(n2)c. O(n1/2)d. O(n3)2. ( )Which is non-linear data structure_____.a. queueb.stackc. treed. sequence list3.( )The worst-time for removing an element from a sequence list (Big-Oh) is .a. O(1)b. O(n)c. O(n2)d. O(n3)4.( )In a circular queue we can distinguish(区分) empty queues from full queues by .a. using a gap in the arrayb. incrementing queue positions by 2 instead of 1c.keeping a count of the number of elementsd. a and c5.( )A recursive function can cause an infinite sequence of function calls if .a.the problem size is halved at each stepb.the termination condition is missingc.no useful incremental computation is done in each stepd.the problem size is positive6.( )The full binary tree with height 4 has nodes.a. 15b. 16c.31d.327. ( )Searching in an unsorted list can be made faster by using .a.binary searchb. a sentinel(哨兵)at the end of the listc.linked list to store the elementsd. a and c8.()Suppose there are 3 edges in an undirected graph G, If we represent graph G with a adjacency matrix, How many “1”s are there in the matrix?a. 3b. 6c. 1d. 99. ( ) Construct a Huffman tree by four leaf whose weights are 9, 2, 5, 7 respectively. The weighted path length is___________.a. 29b. 37c. 46d.4410. Consider the following weighted graph.Consider Dijkstra’s algorithm on this graph to find the shortest paths with s as a starting vertex. Which are the first four vertices extracted from the priority queue by the algorithm (listed in the order they are extracted) ?a. s, y, t, xb. s, y, x, zc. s, t, y, xd. s, y, x, tFig. 111. Here is an array of ten integers:5 3 8 9 1 7 0 26 4Suppose we partition this array using quicksort's partition function and using 5 for the pivot. Which shows the array after partition finishes:a. 5 3 4 2 1 0 7 9 6 8b. 0 3 4 2 1 5 7 9 6 8c. 3 1 0 2 4 5 8 9 6 7d. 3 1 0 2 4 5 8 9 7 6e. None of the aboveII Fill in Blank (10 points)1. For the following program fragment the running time(Big-Oh) is .for ( int i = 0; i < n; i++ )for ( int j = 0; j < =i; j++)s; //s为某种基本操作2. We store a 4×4 symmetric matrix A into an array B with row major order, Store the lower triangle only. the index of element a[2][3] in B is .3.We can use 3 vector type to store value and of non-zero elements in a sparse matrix.4. A______________ is a list where removal and addition occur at the same end . Frequently knowna LIFO (Last-In-First-Out) structure.5.T( n ) = 2T( n/2 )+ cn, T(n) = T( n-1)+cn, T( n ) = O(___________)6. There is a binary tree whose elements are characters. Preorder list of the binary tree is “ABECDFGHIJ” and inorder list of the binary tree is “EBCDAFHIGJ”. Postorder traversal sequence of the binary tree is .7.There are leaf nodes in a full binary tree with n nodes.8.When the input has been sorted ,the running time of insertion sort(Big-Oh) is .9.We sort the sequence(43,02,80,48,26,57,15,73,21,24,66)with shell sort for increment 3, the result is ______ _ .10、In a circular queue, “front” and “rear” are the front pointer and rear pointer respectively. Queue size is “maxsize”. When insert an element in the queue, rear = _________11. A ____________________________________________ is an example of a search tree which is multiway (allows more than two children).12. A tree in which every node is no smaller than its children is termed______________________.III Application of Algorithms(35 points)1.Graph G shown in Fig 2 is a directed graph, please describe G with adjacency matrix and write the orders of breadth first traversal and depth first traversal.Fig.22.The sequence of input keys is shown below:19,1,23,14,55,20,84,27,68,11,10,17A fixed table size of 19 and a hash function H(key)=key%13,with linear probing(线性探测), fill the table below and compute the average length of successful search.3. Show the results of inserting 53,17,78,09,45,65,87 each , one at a time, in a initially empty max heap(大根堆)4. write the sequence of preorder,postorder traversals and add inorder threads in the tree.Fig. 35. Build a Huffman tree and determine Huffman code when the probability distribution(概率分布) over the 8 alphabets ( c1, c2, c3, c4, c5, c6, c7, c8 ) is (0.05, 0.25, 0.03, 0.06, 0.10, 0.11, 0.36, 0.046. Graph G shown in Fig 4 is a directed graph, please describe G with adjacency list and write topological ordering.Fig. 4IV Fill in blank of algorithms.(15)1.Here is single source shortest path algorithm Dijkstra. Fill in blank of the algorithm.class Graph {//图的类定义private:float Edge[NumVertices][NumVertices];float dist[NumVertices];//最短路径长度数组int path[NumVertices];//最短路径数组int S[NumVertices];//最短路径顶点集public:void ShortestPath ( int, int );int choose ( int );};void Graph :: ShortestPath ( int n, int v ){//在具有n 个顶点的带权有向图中, 各边上权值由Edge[i][j]给出。
数据结构与算法分析 C语言描述(第2版)Larry Nyhoff 抽象数据类型 PPT课件
6
Education, Inc. All rights reserved. 0-13-140909-3
Subscript Operation
• We have said elements accessed by name and [ ]
numList[5]
• Consider the [ ] to be an operator
– Program can exceed allowed memory area – Program can give puzzling results
5
Education, Inc. All rights reserved. 0-13-140909-3
Character Arrays
• Elements of an array may be of any type
– Including characters
• Example:
char name [NAME_CAPACITY] = "John Doe";
– The subscript operator – Performs address
translation
• Name of the array is a pointer constant
– The base address
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
– Compiler determines how memory allocated
• Dynamic array
– Allocation takes place at run time
数据结构与算法分析Java语言描述英文版第三版教学设计
•Develop efficient algorithms to solve programming problems.
•Implement and manipulate common data structures.
3.Trees
–Definitions and Properties
–Binary Trees, Binary Search Trees, and Balanced Search Trees
–Heaps
4.Hashing and Graph Algorithms
–Hashing
–Graph Algorithms
–Overview of Data Structures and Algorithms
–Algorithm Analysis
2.Lists, Stacks, and Queues
–Lists and Their Implementations
–Stacks and Queues and Their Implementations
Course Objectives
The primary objective of this course is to provide students with a solid understanding of the fundamental concepts of data structures and algorithms analysis. By the end of the course, students should be able to:
C语言英文版课件.ppt
Shorthand Assignment Operators
Statement with simple
assignment operator a=a+1 a=a–1 a = a * (n+1) a = a / (n+1) a=a%b
Statement with
shorthand operator a += 1 a -= 1 a *= n+1 a /= n+1 a %= b
Example 3.1
The Program shows the use of integer arithmetic to convert a given number of days into months and days.
main()
{
Output
int months, days; EnБайду номын сангаасer days
Non_zero 0
Non_zero 0
Value of the Expression
op_1&&op_2 op_1||op_2
1
1
1
1
1
1
1
1
Examples:
1. if (age > 55 && salary < 1000) 2. if (number < 0 || number > 1000)
The use of shorthand assignment operators has three advantages:
1. What appears on the left-hand side need not be repeated and therefore it becomes easier to write.
数据结构与算法分析Java语言描述英文版第二版教学设计 (3)
Teaching Design of Data Structures and Algorithm Analysis in Java Language Description (2nd Edition) OverviewThe course of data structures and algorithm analysis is an essential subject in computer science education. This course is included in many computer science programs, and students who want to become successful software engineers must master this subject. This document describes the teaching design of the course of data structures and algorithm analysis in Java language description, based on the second edition of the book Data Structures and Algorithm Analysis in Java.Course ObjectivesThe mn objectives of this course are as follows:•To understand the fundamental concepts and principles of data structures and algorithms.•To develop skills in the analysis and design of algorithms.•To implement data structures and algorithms in Java programming language.•To learn how to evaluate the performance of algorithms.•To learn how to select the appropriate data structures and algorithms for solving different problems.Course ContentThe following topics will be covered in this course:•Introduction to data structures and algorithm analysis•Mathematical background•Algorithm analysis•Arrays and linked lists•Stacks and queues•Trees•Hash tables•Priority queues•Sorting algorithms•Searching algorithms•Graph algorithmsTeaching MethodsThe course will be taught in a combination of lectures, assignments, and practical sessions. The lectures will be used to introduce the fundamental concepts and principles of data structures and algorithm analysis. The assignments will be used to practice the skills acquired in the lectures. The practical sessions will be used to implement data structures and algorithms in Java programming language and to conduct performance analysis.Assessment MethodsThe assessment of this course will be based on the following: •Assignments•Midterm Exam•Final ExamThe assignments will be used to assess the understanding of the concepts and principles of data structures and algorithm analysis. The midterm exam will be used to assess the skills in the analysis and design of algorithms. The final exam will be used to assess the overall understanding of the course.TextbookThe textbook for this course is Data Structures and Algorithm Analysis in Java (2nd Edition) by Mark Allen Weiss.ConclusionThis document has described the teaching design of the course ofdata structures and algorithm analysis in Java language description. This course is essential for computer science students and software engineers, and mastering this subject will improve their software development skills. The teaching design outlined in this document will enable students to achieve the course objectives and become competent in data structures and algorithm analysis.。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Head pointer ptr = 0110
ZHAO
QIAN
NULL
Insertion
ptr node
b temp
§2 The List ADT
takes O(1) time. ... an
NULL
a1
...
ai
ai+1
temp->next =
node->next
node->next = temp
Coefficient Exponent Next
typedef struct poly_node *poly_ptr; struct poly_node { int Coefficient ; /* assume coefficients are integers */ int Exponent; poly_ptr Next ; }; typedef poly_ptr a ; /* nodes sorted by exponent */
llink rlink typedef struct node *node_ptr ; item typedef struct node { node_ptr llink; Uhhh ... Then I‟ll have to Don‟tptr->llink->rlink ptr = we have element item; go from the 1st node again. enough headache already? node_ptr rlink; ptr->rlink->llink But hey, why do I=wantta }; Why do we need
MaxSize has to be estimated. Find_Kth takes O(1) time. Insertion and Deletion not
only take O(N) time, but also involve a lot of data movements which takes time.
§2 The List ADT
ADT: Objects: ( item0, item1, , itemN1 ) Operations:
Finding the length, N, of a list. Why after? Printing all the items in a list. Making an empty list. Finding the k-th item from a list, 0 k < N. Inserting a new item after the k-th item of a list, 0 k < N. Deleting an item from a list. Finding next of the current item from a list. Finding previous of the current item from a list.
takes O(1) time. ... an
NULL
a1 pre->next =
...
ai
ai+1
node->next
free ( node )
Question: How can we delete the first node from a list? Answer: We can add a dummy head node to a list.
Finding degree, max { ei }, of a polynomial. Addition of two polynomials. Subtraction between two polynomials. Multiplication of two polynomials. Differentiation of a polynomial.
【Representation 1】 typedef struct { int CoeffArray [ MaxDegree + 1 ] ; int HighPower; } *Polynomial ;
Try to apply MultPolynomial (p.53) I likeN *N1000 easy to complexity O( =it! 2 ) +5x time Really? WhatIt’s the 14+1 and is 1 On P1(x) 10x of the operations, implement mostwith that? polynomials What’s wrong 2x1492+11x+5 for finding the product of two P2(x) = 3x1990 suchof degree N Multiplication. as Add and and N ? 1 2 -- now do you see my point?
§2 The List ADT
S5
C1
C2
C3
C4
§2 The List ADT
3. Cursor Implementation of Linked Lists (no pointer) Features that a linked list must have:
a) The data are stored in a collection of structures. Each structure contains data and a pointer to the next structure. b) A new structure can be obtained from the system‟s global memory by a call to malloc and released by a call to free. Cursor Element Space Next
Question: What will happen if the order of the two steps is reversed?
Question: How can we insert a new first item?
Deletion
ptr pre
b node
§2 The List ADT
2. Linked Lists
Address 0010 0011 0110 1011 Data SUN QIAN ZHAO LI Pointer 1011 0010 0011 NULL
ptr ZHAO SUN
§2 The List ADT
QIAN LI
NULL
To link „ZHAO‟ and „QIAN‟:
a
am1 em1
……
a0
e0
NULL
Multilists
§2 The List ADT
〖Example〗 Suppose that we have 40,000 students and 2,500
courses. Print the students‟ name list for each courses, and print the registered classes‟ list for each student.
§2 The List ADT
【Representation 2】 Given: A( x ) am 1 x em1 a0 x e0 We represent each term as a node Declaration:
§2 The List ADT
where em 1 em 2 e0 0 and ai 0 for i 0, 1, , m 1.
CHAPTER 3
Lists, Stacks, an Type (ADT)
【Definition】Data Type = { Objects } { Operations } 〖Example〗 int = { 0, 1, 2, , INT_MAX, INT_MIN } { , , , , , } 【Definition】An Abstract Data Type (ADT) is a data type that is organized in such a way that the specification on the objects and specification of the operations on the objects are separated from the representation of the objects and the implementation on the operations.
An empty list :
H
Two Applications
§2 The List ADT
The Polynomial ADT
Objects : P ( x ) = a1 x e1 + + an x en ; a set of ordered pairs of < ei , ai > where ai is the coefficient and ei is the exponent. ei are nonnegative integers. Operations:
1. Simple Array implementation of Lists array[ i ] = itemi Sequential mapping
Address Content …… …… array+i itemi array+i+1 itemi+1 …… ……