You are on page 1of 9
Ce we Ce ee ea RETURN ThieNodePty // will veturn null pointer if gearch item not found NDFUXCTION TASK 23.06 Write program code to implement a binary search tree, 23.08 Stacks In Chapter 13 (Section 13.08) we looked at the conceptual data structure ofa stack A stack can be implemented using @ 1D array Figure 23,06 shows a stack containing four data items. For conceptual reasons the aray elements are numbered from the bottom up. Note that paseorstackPoinver will always point to element 0 of the array, ‘TopofstackPointer will vary, will increase when an item is pushed onto tre stack and itll decrease when an item is popped off the stack, When the stack is empty, ‘TopofstackPoincer will have the value + TopofstackPointer Figure 23.06 A stack 2 c 8 A Create a new stack U mulipointer should be set to -1 if using array element with index 0 CONSTANT EMPTYSTRING = =" CONSTANT NullPointer = = CONSTANT MaxstackSize = @ DECLARE BaseGfStackPoiner + INTEGER DECLARE TopofstackPointer + INTEGER DECLARE stack ; AKRAY[L ; MaxStackSize ~ 1] OF STRING: PROCEDURE Initialisestack BaseofstackPointer © 0 I] set base of stack pointer ‘TopotstackPointer « NullPointer // set top of stack pointer ENDPROCEDURE, Push an item onto the stack PROCEDURE Push (Newton) IP TopofstackPointer < MaxstackSize - 1 THEN // there is epace on the stack UW increnent top of stack pointer nopofStackPointer = TopofStackPointer + 1 U add item to top of stack stack|Topofstackzoincer] + Newizen ENDIF ENDPROCEDURE, ‘Cambridge International AS & A Level Computer Science Pop an item off the stack PUNCTION Pops) DBCLARE Téem + STRING IF ToposstackPointer > wallpointer max // the: east one iten on the stack 11 pop iten oft the top of stack tem © Stack(ToporstackPointer] top ef stack pod: i dace TopofstackPointer IF ‘TASK 23.07 1. Write a program to impleme: to test the subroutines, he above pseudocode subroutines, Add a menu 2. Write a program to implement a stack as a liked lst. Note that the adding and removing of nades is much simpler than for an ordered linked list 23.09 Queues f dat jeue. Aqueue can be implemented using a 1D array. Figure 23.07 shows a queue containing ‘ve deta items Chapt 13 (Section 13,09} we locke: he conceptual data structure of ag ProntofgueuePointer always points to the first elementin the queve, th elementto be taken from the queve. the queve, Before ano! Note the dofQuewePointer always points to the last elementin queue, the EndoroueePoin mented hen acjusting either pointer the possibility of wrap-round hes to be tested To make it easier to test whether the queue is empty or full, 2 counter variable can be used. {tOfqueuePointe: ° + EndofgueuePointer + EndofgueuePointer + FrontofgueuePointer Figure 23.07 A queue before wrap-round Figure 23.08 Aqueue with wrap-round Create anew queue if using arvay elenent index 0 EMT: CONSTANT Maxqueuesize = 4 DECLARE EndofqueuePots INTs: DECLARE Nunberingueue + INTEGER CLARE Queue : ARRAY[O : MaxQueu! RE Initialisegueue ontofgueuePointer « Wa Pointer // set front of aueue pointer Ce we Ce ee ea EndotgueuePointer « Wullpointer // get end of queue pointer Numberingueue + 0 Hf no elements im guexe ENDPROCEDURE, Add an item to the queue PROCEDURE AdaToQueue(Newrten) IP NunberIngueue < Maxgueuesize THEN —// there is space in the queue Wf Snerenent end of queue pointer EndofquauePointer « EndofqueuePointer + 2 U check for weap-round IF EndofQuauePointer > Maxgueuesize ~ 1 THEN // wrap to beginning of array ndofqueuePointer « 0 UJ a0a icem to end of queue ENDIF Queue(EndofqueuePointer) « Newrtem J inexenent counter Numberingueue + Numberingueue + 1 ENDIE ENDPROCEOURR, Remove an item from the queue FUNCTION RemoveFronqueue() DECLARE Tom + STRING j= | BE Mumbezingueue > 0 SHEN // thre ie at leaet one Stem in che queue Uf remove iven Ezom the front. of the queue ten © queuelFrontofquevePointes) Shumhexinguewe = Mumbesingweue = 2 IF tunberinguese ~ 0 THEN // Sf queue empty, reset pointers CALE, snitialisagueue ese /] snczonent front of quese pointer FrontotQueuePointer « ProntofgueueFeinter + 1 i] check for weap-rosnd AP ErontofgueueFosnter > Maxoueuesize = 2 THEN // wrap to beginning of azray Feontofqueuerointer © 9 Nour wore RETURN Then TASK23.08 1. Write a program to implement the above pseudocode subroutines. Add a menu to test the subroutines. 2. Write program code to implement a queue as a linked lst. You may find it helpful ‘© introctice another pointer that always points to the end of the queue. You wil need to update it when you add @ new node to the queue, ‘Cambridge International AS & A Level Computer Science 23.10 Graphs Im Computer Science a grap’ is an ADT consisting of vertices (nodes) and edges. Graphs are used to record relationships between things. For uses of graphs in Alsee Chapter 22, Section 22,02. Asimple graph is shown in Figure london Underground map shown in Figure 12.02 Ch . ' Figure 23.08 Graph showing part of the London Underground map a small part of The vertices labelled A to Fare the underground stations and the edges represent train ines connecting the stations. For example, you can take a train directly from B to D, To get from B to F,you have to travel via Cor E, Two vertices connected by an edge are known as, neighbours Alabelled (weighted) grap! woights to Fig vay? C-O-~-O Figure 23.10 Weighted graph showing travelling times between stations 12s edges with values representing something. In our example 10 to show the time it takes to travel between stations: faphs can be directed or undirected sin Figure 23.10), Travel times may vary depending con the direction of travel. This can be shown in a directed graph (see Figure 23.11 Chia er() Figure 23.11 Directed graph Sometimes one direction may not be available. For example, ithe line from B to Dis blocked, ‘esented as shown in Figure 23.12. Ce we Ce ee ea 3 3 3 3 33 8 kk a2 2 \—2 4 4 Figure 23.12 Directed graph We can use a graph to plan ajourney. Using Figure 23.12, we want to travel from C to D, so we ‘can either use the route € B A (11 minutes) or the route C FED (8 minutes). For the return Journey we can use D BC (7 minutes} TASK 23.09 Draw the labelled edges for a directed graph of a road system where: + AtoBis2km, and itis a one-way system + Dto Ais km, and is one-way + BtoDis3kmandis one-way + BtoCisAkm + CtoEis? km + Dto Eis Skm, OO © © © Toimplement a graph, we can use an adjacency matrix or an adjacency lst. ‘An adjacency matrix stores the relationship between every vertex to all other vertices. For an unweighted graph, a 1 represents an edge, ano edge. When weights are to be recorded, the ‘weight replaces the 1, Instead of a0, we use the infinity symbol, ara rae ara afi @ -[3 5 2 fe pa ipo tlle l= a[i{elole|a -[3[-[=[=[2 1 [2 fe rpe| sfel=[=[2[=] o[?fe of? | =[el=[4 2 | afela ra -eee Rl] Table 22.01 Table 23.02 Agjaceney matrix for Figure 23.09 Adjacency matrix for Figure 23.12 a eee ee Re carat’ An acjacency list stores the relationship between every vertex to all relevant vertices. An entry is made only when there is an edge between two vertices. For @ weighted graph, the connection as well as the weights stored in the list enn 2.350.5 A363, E4 Bah? A5.B.46,2 8,450,472 C33 Table 23.03, Table 23.04 Adjacency lst for Figure 23.09 Adjacency list for Figure 23.12 TASK 23.10 Construct an adjacency matrix and an adjacency list to represent your graph from Task 23.09, 23.11 Hash tables Ife want to store records in an array and have direct ace concept of ahash table 5 to records, we can use the The idea behind a hash table is that we calculate an address (the array index) from the key value of the record and store the record at this address. When we search for arecord, we calculate the address from the key and go to the calculated address to find the record Calculating an address from a key is called ‘hashing’ Finding a hashing function that will give a unique address fram a unique key value's very dificult. two diferent key values hash to the same adress this is called a ‘collision’ There are different ways to handle calisions: + chaining: create a linked list fr collisions with start pointer atthe hashed address. + using overflow areas all collisions are stored in a separate overflow area, known as ‘closed hashing + using neighbouring slots: perform a linear search from the hashed address to find an empty slot, known 2s ‘open hashing’ reciente Calculating addresses in a hash table Assume we want to store customer records in a 1D array Hashrable [a + n). Each customer has a unique customer ID, an integer in the range 10001 to 93938. ‘Wenced to design a suitable hashing function. The result of the hashing function should be such that every index of the array can be addressed directly, The simplest hashing function gives us addresses between 0 andn (Continued) Ce we Ce ee ea FUNCTION Hash(Key) RETURNS INTEGER Address ~ Key MoD(n + 1) RETURN Addvese ENDPUNCTION For illustrative purposes, we choose n to be 9. Our hashing function is Index © CustomerID "od 10 \We want to store records with customer IDs: 45876, 32390, 95312, 64636, 22467. We can store the first three ‘ecords in their correct slots, as shown in Figure 23.13, o @ 2 8 WW 8 6 7 @ 32390 95312 45876 Figure 23.13 Ahash table without collisions The fourth record key (64636) also hashes to indexs. This slotis already taken; we have a collision. we store cour record here, we lose the previous record. To resolve the collision, we can choose to store our record in the next avallable space, as shown in Figure 23.14, Oo Oo 2 eo Ww 8 oom os 32390 e512 “45876 | 64626 Figure 23.14 Ahash table with a collision resolved by open hashing The fifth record key (22467) hashes to index 7. This slot has been taken up by the previous record, so again we ‘eed to use the next available space (Figure 23.15) o @ 2 8 Ww § 6 7 32390 95312 45876 | 60636 | 23467 Figure 23.15 Ahash table with two collisions resolved by open hashing When searching for record, we need to allow for these out-of-place records. We know ifthe record we are searching for does not exist in the hash table when we came across an unoccupied slot. \We will now develop algorithms to insert a record into a hash table and to search for a record in the hash table using its record key. The hash tableis a 1D artayRashTable (0 Max] OF Recore. ‘The records stored in the hash table have a unique key stored infield Key. Insert a record into a hash table PROCEDURE Insert (NesRecord) Index « Hash{NewRecord. Key) WHILE HashTable[Index] No? empty DO Index « Index 41 // go to next alet to check if empty IF Index > Max // beyond table boundary? THEN // wrap around to beginning of table Index + 0 ENDWETLE ‘Cambridge International AS & A Level Computer Science aehTable(index] + NewRecord Find a record in a hash table FUNCTION FindRecord(SearchKey) RETURNS & Index « Hash(SearchKey) WHILE ash?able|Index).Key <> Search AND [aghTablelIndex] NOT empty) DO Index © Index + 1 // go to next elet If Index > Max // beyond table boundary? THEN // weap around to beginning of table ox = 6 IF HaghTable(index) wi empty // if record found RETURN HashTable[Index] // return the record FUNCTION 23.12 Dictionaries tion of key’ wary is aco alue pairs. The key nyou use to up the recuired value. For example, if you use an English-French dictionary to look up the nglish word ‘book, you wil ind the French equivalent word ‘livre. Areal-wo organised in alphabetical order of keys ictionary is AN ADT dictionary in computer science i implemented using a hash table (see Section 23.11) soth access method. be looked up using a dire Python, VB.NET and Java have a builtin ADT dictionary class. unglis! nck =) # AnglighFrench[*book"] = "Livre" # add a key-value pair co che dictionary English¥rench["pen"] = "stylo' print (ing) ishPrench(*book tal # acceas 4 value in the dictionary ative method of setting up a dictionary Computingvarne = ("Zoolean* ; "ean be TRUE or FALSE, "RitY : "0 or 2") print (ConputingTerne: lere ere some examples of V8 dictionaries: bim EnglishFrench As New Dictionarylof string, string) ingLishPrench.Add ("book English?rench.Add("pen", "stylo" Console WriteLine(Englishrrench book") computing! ‘can be TRUE or FALS! console, hriveLsne (Computing? Console ReadLine() Ce we Ce ee ea Here are some examples of Java dictionaries (the Dictionary class s obsolete, use HashMap instead) import java.util.Map; import java.uti? HashMap; Mapestring, String> english?rench = new HashMapestring, String>{); englichfrench.put(*book", “livre"); englishFrench.put(tpent, "style; System.cut.prin:In(englishFrench.get("book")}; Mapestring, String» computirgTerms = new HashMapestring, Strings{}; conputingTerms.put(*Boolean", "can be TRUE or FALSE"); computingterms-put("Bit", "0 or a"; System.out.printIn{computingTerns get ("Bit"); ‘There are many builtin functions for Python, VB and Java dictionaries. These are beyond the scope of this book, However, we need to understand how dictionaries are implemented. The following pseudocode shows how to create a new dictionary. ‘ype Dictionaryencry DECLARE Key STRING DECLARE Valve : STRING DECLARE English?rench ARRAY(O : 988) OF DictionaryBntry // empty Bictionary, TASK 23.11 jo | Write pseudocode to: insert a key-value pairinto a dictionary © lookup a value in a dictionary. Use the hashing function from Worked Example 23.01 23.13 Big O notation problem can be solved in cifferent ways, with different algorithms, Clearly, we want to Use time and memory eficiently. Away of comparing the eficiency of algoritams has been devised using order of growth as a function ofthe size of tre input. Big 0 notation is used to classify algorithms according :o how their running time (or space requirements) grows as the input size grows. The letter 0 is used because the growth rate of a function is also re‘erred 10 a5 order ofthe function: The worst-case scenario is used when calculating the order of growth for very large data sets. Consider the linear search algorithm in Chapter 13, Worked Example 13.02. The worst case ‘scenar'o is thatthe iter searched foris the last item in the lst. The longer the lst, the more ‘comparisons have to be made. Ifthe lists twice as long, twice as many comparisons have to be made. Generally, we can say the order of growthis linear. We write this as O(n, where mis the size of the data set. Consider the bubble sort algorithm for the worst case scenario. unsorted = a - 2 FOR G0 TOR 2 FOR j + 0 70 Unsorted - 1 Tr Mytiettj) > Mytiset) + 21

You might also like