id
int64
0
25.6k
text
stringlengths
0
4.59k
21,500
machine (jvmmaintains stack whose elements are descriptors of the currently active (that isnonterminatedinvocations of methods these descriptors are called frames frame for some invocation of method "foolstores the current values of the local variables and parameters of method foolas well as information on method "cool...
21,501
the jvm keeps special variablecalled the program counterto maintain the address of the statement the jvm is currently executing in the program when method "coolinvokes another method "fool"the current value of the program counter is recorded in the frame of the current invocation of cool (so the jvm will know where to ...
21,502
suspended method understanding call-by-value parameter passing the jvm uses the java stack to perform parameter passing to methods specificallyjava uses the call-by-value parameter passing protocol this means that the current value of variable (or expressionis what is passed as an argument to called method in the case ...
21,503
postorder traversalwhich is exactly the algorithm the jvm uses we described that algorithm in recursive wayhowevernot in way that explicitly uses an operand stack neverthelessthis recursive description is equivalent to nonrecursive version based on using an operand stack implementing recursion one of the benefits of us...
21,504
because calling factorial( returns immediately without invoking itself recursively the run-time stack allows for method factorial(to exist simultaneously in several active frames (as many as at some pointeach frame stores the value of its parameter as well as the value to be returned eventuallywhen the first recursive ...
21,505
the java virtual machine definition requires that the memory heap be able to quickly allocate memory for new objectsbut it does not specify the data structure that we should use to do this one popular method is to keep contiguous "holesof available free memory in doubly linked listcalled the free list the links joining...
21,506
next-fit algorithm spreads fragmentation more evenly throughout the memory heapthus keeping search times low this spreading also makes it more difficult to allocate large blockshowever the worst-fit algorithm attempts to avoid this problem by keeping contiguous sections of free memory as large as possible garbage colle...
21,507
once this process has completedwe then scan through the memory heap and reclaim any space that is being used for an object that has not been marked at this timewe can also optionally coalesce all the allocated space in the memory heap into single blockthereby eliminating external fragmentation for the time being this s...
21,508
in ' adjacency list thuswhether we use this edge-swapping trick or count identifierwe can implement dfs in-place without affecting its asymptotic running time external memory and caching there are several computer applications that must deal with large amount of data examples include the analysis of scientific data set...
21,509
specificallythe two levels that matter most depend on the size of the problem we are trying to solve for problem that can fit entirely in main memorythe two most important levels are the cache memory and the internal memory access times for internal memory can be as much as to times longer than those for cache memory i...
21,510
it is actually reasonable assumption to make one justification for this assumption is that it is often necessary to assume that all memory accesses take the same amount of timesince specific device-dependent information about memory sizes is often hard to come by in factinformation about memory size may be impossible t...
21,511
the internal memory size the concept of bringing data into primary memory is called cachingand it is motivated by temporal locality forby bringing data into primary memorywe are hoping that it will be accessed again soonand we will be able to respond quickly to all the requests for this data that come in the near futur...
21,512
cache memory that has "slotsthat can contain web pages we assume that web page can be placed in any slot of the cache this is known as fully associative cache as browser executesit requests different web pages each time the browser requests such web page lthe browser determines (using quick testif is unchanged and curr...
21,513
random or pseudo+random number generator the overhead involved in implementing this policy is an ( additional amount of work per page replacement moreoverthere is no additional overhead for each page requestother than to determine whether page request is in the cache or not stillthis policy makes no attempt to take adv...
21,514
existing pagesfor exampleusing special pointers or "locators if is implemented with sorted sequence based on linked listthen the overhead for each page request and page replacement is ( when we insert page in or update its keythe page is assigned the highest key in and is placed at the end of the listwhich can also be ...
21,515
we refer to this count as the / complexity of the algorithms involved some inefficient external-memory dictionaries let us first consider the simple dictionary implementations that us list to store entries if the list is implemented as an unsorteddoubly linked listthen insert and remove can be performed with ( transfer...
21,516
an ( ,btreewhere and are integerssuch that < <( )/ is multiway search tree with the following additional restrictionssize propertyeach internal node has at least childrenunless it is the rootand has at most children depth propertyall the external nodes have the same depth proposition the height of an (abtree storing en...
21,517
handled in ( ,btrees the insertion algorithm for an (abtree is similar to that for ( , tree an overflow occurs when an entry is inserted into -node vwhich becomes an illegal ( )-node (recall that node in multi-way tree is -node if it has children to remedy an overflowwe split node by moving the median entry of into the...
21,518
we restrict our discussion here to the / complexity of -trees figure -tree of order an important property of -trees is that we can choose so that the children references and the keys stored at node can all fit into single disk blockimplying that is proportional to this choice allows us to assume that and are also propo...
21,519
the algorithmic problem using as few block transfers as possible the most classic domain for such external-memory algorithms is the sorting problem multi-way merge-sort an efficient way to sort set of objects in external memory amounts to simple external-memory variation on the familiar merge-sort algorithm the main id...
21,520
and we associate the smaller of the two with we repeat this comparison test at the next level up in tand the nextand so on when we reach the root of twe will associate the smallest object from among all the lists with this completes the initialization for the -way merge (see figure figure -way merge we show five-way me...
21,521
- describein detailthe insertion and removal algorithms for an ( ,btree - suppose is multi-way tree in which each internal node has at least five and at most eight children for what values of and is valid ( ,btreer- for what values of is the tree of the previous exercise an order- -treer- show each level of recursion i...
21,522
- show how to implement dictionary in external memoryusing an unordered sequence so that insertions require only ( transfers and searches require ( /btransfers in the worst casewhere is the number of elements and is the number of list nodes that can fit into disk block - change the rules that define red-black trees so ...
21,523
section so that the union and find operations each use at most (logn/logbdisk transfers - suppose we are given sequence of elements with integer keys such that some elements in are colored "blueand some elements in are colored "red in additionsay that red element pairs with blue element if they have the same key value ...
21,524
implement the -tree data structureassuming block size of , and integer keys test the number of "disk transfersneeded to process sequence of dictionary operations - implement an external-memory sorting algorithm and compare it experimentally to any of the internal-memory sorting algorithms described in this book notes k...
21,525
useful mathematical facts in this appendix we give several useful mathematical facts we begin with some combinatorial definitions and facts logarithms and exponents the logarithm function is defined as log if bc the following identities hold for logarithms and exponents log ac log log log / log log log ac clog log (log...
21,526
ab ab ab / ( ) ( ) / <( ) / / the natural logarithm function lnx log xwhere is the value of the following progressione / / / **in additionex / / / **ln( xx / / / **there are number of useful inequalities relating to these functions (which derive from these definitionsproposition if / <ln( < proposition for <ex < / prop...
21,527
*****( ) the binomial coefficient is which is equal to the number of different combinations one can define by choosing different items from collection of items (where the order does not matterthe name "binomial coefficientderives from the binomial expansionwe also have the following relationships proposition if <= <nth...
21,528
there are number of useful facts about summations proposition factoring summationsprovided does not depend upon proposition reversing the orderone special form of summation is telescoping sumwhich arises often in the amortized analysis of data structure or algorithm the following are some other facts about summations t...
21,529
proposition for any real number there is also combination of the two common formscalled the linear exponential summationwhich has the following expansionproposition for the nth harmonic number is defined as proposition if is the nth harmonic numberthen is ln th( basic probability we review some basic facts from probabi...
21,530
basic properties with respect to events defined from pr( pr( <pr( < for any if , and ab othen pr(aubpr( +pr(btwo events and are independent if pr(abpr( )*pr(ba collection of events { is mutually independent if pr( ik pr( pr( ***pr( ik for any subset { , , ik the conditional probability that an event occursgiven an even...
21,531
and (cxce(xexample let be random variable that assigns the outcome of the roll of two fair dice to the sum of the number of dots showing then ( justificationto justify this claimlet and be random variables corresponding to the number of dots on each die thusx ( they are two instances of the same functionand (xe( ( ( ea...
21,532
the following rule proposition ( 'hopital' rule)if we have limn- (nand we have limn- ( +then limn- ( )/ (nlim nf'( )/ '( )where '(nand '(nrespectively denote the derivatives of (nand (nin deriving an upper or lower bound for summationit is often useful to split summation as followsanother useful technique is to bound s...
21,533
[ adelson-velskii and landisan algorithm for the organization of informationdoklady akademii nauk sssrvol pp english translation in soviet math dokl - [ aggarwal and vitterthe input/output complexity of sorting and related problemscommun acmvol pp - [ ahoalgorithms for finding patterns in stringsin handbook of theoreti...
21,534
which is not necessarily following the hierarchical structure such data structure is termed as graph array is container which can hold fix number of items and these items should be of the same type most of the data structures make use of arrays to implement their algorithms following are the important terms to understa...
21,535
int float double void wchar_t insertion operation insert operation is to insert one or more data elements into an array based on the requirementa new element can be added at the beginningendor any given index of array herewe see practical implementation of insertion operationwhere we add data at the end of the array al...
21,536
whilej >kla[ + la[ ] la[kitemprintf("the array elements after insertion :\ ")for( <ni++printf("la[% % \ "ila[ ])when we compile and execute the above programit produces the following result output the original array elements are la[ la[ la[ la[ la[ the array elements after insertion la[ la[ la[ la[ la[ la[ deletion ope...
21,537
lve demo #include void main(int la[{ , , , , }int int ijprintf("the original array elements are :\ ")for( <ni++printf("la[% % \ "ila[ ]) kwhilej nla[ - la[ ] - printf("the array elements after deletion :\ ")for( <ni++printf("la[% % \ "ila[ ])when we compile and execute the above programit produces the following result ...
21,538
search operation you can perform search for an array element based on its value or its index algorithm consider la is linear array with elements and is positive integer such that <= following is the algorithm to find an element with value of item using sequential search start set repeat steps and while if la[jis equal ...
21,539
la[ found element at position update operation update operation refers to updating an existing element from the array at given index algorithm consider la is linear array with elements and is positive integer such that <= following is the algorithm to update an element available at the th position of la start set la[ -...
21,540
la[ la[ la[ la[ la[
21,541
sparse matrix and its representations matrix is two-dimensional data object made of rows and columnstherefore having total values if most of the elements of the matrix have valuethen it is called sparse matrix why to use sparse matrix instead of simple matrix storagethere are lesser non-zero elements than zeros and thu...
21,542
for (int ++for (int ++if (sparsematrix[ ][ ! compactmatrix[ ][kicompactmatrix[ ][kjcompactmatrix[ ][ksparsematrix[ ][ ] ++for (int = < ++for (int = <sizej++printf("% "compactmatrix[ ][ ])printf("\ ")return
21,543
stack stack is an abstract data type (adt)commonly used in most programming languages it is named stack as it behaves like real-world stackfor example deck of cards or pile of platesetc real-world stack allows operations at one end only for examplewe can place or remove card or plate from the top of the stack only like...
21,544
when data is pushed onto stack to use stack efficientlywe need to check the status of stack as well for the same purposethe following functionality is added to stacks peek(get the top data element of the stackwithout removing it isfull(check if stack is full isempty(check if stack is empty at all timeswe maintain point...
21,545
algorithm of isempty(function begin procedure isempty if top less than return true else return false endif end procedure implementation of isempty(function in programming language is slightly different we initialize top at - as the index in array starts from so we check if the top is below zero or - to determine if the...
21,546
endif top top stack[topdata end procedure implementation of this algorithm in cis very easy see the following code example void push(int dataif(!isfull()top top stack[topdataelse printf("could not insert datastack is full \ ")pop operation accessing the content while removing it from the stackis known as pop operation ...
21,547
begin procedure popstack if stack is empty return null endif data stack[toptop top return data end procedure implementation of this algorithm in cis as follows example int pop(int dataif(!isempty()data stack[top]top top return dataelse printf("could not retrieve datastack is empty \ ")
21,548
stack applications three applications of stacks are presented here these examples are central to many activities that computer must do and deserve time spent with them expression evaluation backtracking (game playingfinding pathsexhaustive searching memory managementrun-time environment for nested language features exp...
21,549
+ *bc abc*( ( *+ab-cd ab+cd- * - * * -*bb ** ac bb* * * postfix evaluation algorithm assume we have string of operands and operatorsan informalby hand process is scan the expression left to right skip values or variables (operands when an operator is foundapply the operation to the preceding two operands replace the tw...
21,550
order of popping is the order in the output if the current input token is '('push it onto the stack if the current input token is ')'pop off all operators and append them to the output string until '(is poppeddiscard the '( if the end of the input string is foundpop all operators and append them to the output string th...
21,551
when method/function is called an activation record is createdits size depends on the number and size of the local variables and parameters the base pointer value is saved in the special location reserved for it the program counter value is saved in the return address location the base pointer is now reset to the new b...
21,552
queue queue is an abstract data structuresomewhat similar to stacks unlike stacksa queue is open at both its ends one end is always used to insert data (enqueueand the other is used to remove data (dequeuequeue follows first-in-first-out methodologyi the data item stored first will be accessed first real-world example ...
21,553
as follows algorithm begin procedure peek return queue[frontend procedure implementation of peek(function in programming language example int peek(return queue[front]isfull(as we are using single dimension array to implement queuewe just check for the rear pointer to reach at maxsize to determine that the queue is full...
21,554
return false endif end procedure if the value of front is less than min or it tells that the queue is not yet initializedhence empty here' the programming code example bool isempty(if(front rearreturn trueelse return falseenqueue operation queues maintain two data pointersfront and rear thereforeits operations are comp...
21,555
rear rear queue[reardata return true end procedure implementation of enqueue(in programming language example int enqueue(int dataif(isfull()return rear rear queue[reardatareturn end procedure dequeue operation accessing data from the queue is process of two tasks access the data where front is pointing and remove the d...
21,556
return underflow end if data queue[frontfront front return true end procedure implementation of dequeue(in programming language example int dequeue(if(isempty()return int data queue[front]front front return data
21,557
linked list linked list is sequence of data structureswhich are connected together via links linked list is sequence of links which contains items each link contains connection to another link linked list is the second most-used data structure after array following are the important terms to understand the concept of l...
21,558
and (rightnodethen point next to between (leftnodenewnode next -rightnodeit should look like this nowthe next node at the left should point to the new node leftnode next -newnodethis will put the new node in the middle of the two the new list should look like this similar steps should be taken if the node is being inse...
21,559
deletion is also more than one step process we shall learn with pictorial representation firstlocate the target node to be removedby using searching algorithms the left (previousnode of the target node now should point to the next node of the target node leftnode next -targetnode nextthis will remove the link that was ...
21,560
make it point to its previous node we have to make sure that the last node is not the lost node so we'll have some temp nodewhich looks like the head node pointing to the last node nowwe shall make all left side nodes point to their previous nodes one by one except the node (first nodepointed by the head nodeall nodes ...
21,561
struct node *current null//display the list void printlist(struct node *ptr headprintf("\ ")//start from the beginning while(ptr !nullprintf("(% ,% ",ptr->key,ptr->data)ptr ptr->nextprintf(]")//insert link at the first location void insertfirst(int keyint data//create link struct node *link (struct node*malloc(sizeof(s...
21,562
//is list empty bool isempty(return head =nullint length(int length struct node *currentfor(current headcurrent !nullcurrent current->nextlength++return length//find link with given key struct nodefind(int key//start from the first link struct nodecurrent head//if list is empty if(head =nullreturn null//navigate throug...
21,563
return current//delete link with given key struct nodedelete(int key//start from the first link struct nodecurrent headstruct nodeprevious null//if list is empty if(head =nullreturn null//navigate through list while(current->key !key//if it is last node if(current->next =nullreturn nullelse //store reference to current...
21,564
int ijktempkeytempdatastruct node *currentstruct node *nextint size length() size for size ++ -current headnext head->nextfor +if current->data next->data tempdata current->datacurrent->data next->datanext->data tempdatatempkey current->keycurrent->key next->keynext->key tempkeycurrent current->nextnext next->nextvoid ...
21,565
void main(insertfirst( , )insertfirst( , )insertfirst( , )insertfirst( , )insertfirst( , )insertfirst( , )printf("original list")//print list printlist()while(!isempty()struct node *temp deletefirst()printf("\ndeleted value:")printf("(% ,% ",temp->key,temp->data)printf("\nlist after deleting all items")printlist()inser...
21,566
printf("element not found ")delete( )printf("list after deleting an item")printlist()printf("\ ")foundlink find( )if(foundlink !nullprintf("element found")printf("(% ,% ",foundlink->key,foundlink->data)printf("\ ")else printf("element not found ")printf("\ ")sort()printf("list after sorting the data")printlist()reverse...
21,567
list after deleting an item( , ( , ( , ( , ( , element not found list after sorting the data( , ( , ( , ( , ( , list after reversing the data( , ( , ( , ( , ( ,
21,568
polynomial list polynomial (xis the expression in variable which is in the form (ax bxn- jxk)where abc fall in the category of real numbers and 'nis non negative integerwhich is called the degree of polynomial an important characteristics of polynomial is that each term in the polynomial expression consists of two part...
21,569
the exponent part the coefficient part adding two polynomials using linked list given two polynomial numbers represented by linked list write function that add these lists means add the coefficients who have same variable powers exampleinput st number ^ ^ ^ nd number ^ ^ output ^ ^ ^ input st number ^ ^ ^ nd number ^ ^...
21,570
int coeffint powstruct node *next}void create_node(int xint ystruct node **tempstruct node * *zz *tempif( =nullr =(struct node*)malloc(sizeof(struct node)) ->coeff xr->pow *temp rr->next (struct node*)malloc(sizeof(struct node)) ->nextr->next nullelse ->coeff xr->pow
21,571
->nextr->next nullvoid polyadd(struct node *poly struct node *poly struct node *polywhile(poly ->next &poly ->nextif(poly ->pow poly ->powpoly->pow poly ->powpoly->coeff poly ->coeffpoly poly ->nextelse if(poly ->pow powpoly->pow poly ->powpoly->coeff poly ->coeffpoly poly ->nextelse poly->pow poly ->powpoly->coeff pol...
21,572
poly poly ->nextpoly->next (struct node *)malloc(sizeof(struct node))poly poly->nextpoly->next nullwhile(poly ->next |poly ->nextif(poly ->nextpoly->pow poly ->powpoly->coeff poly ->coeffpoly poly ->nextif(poly ->nextpoly->pow poly ->powpoly->coeff poly ->coeffpoly poly ->nextpoly->next (struct node *)malloc(sizeof(str...
21,573
void show(struct node *nodewhile(node->next !nullprintf("%dx^% "node->coeffnode->pow)node node->nextif(node->next !nullprintf(")int main(struct node *poly null*poly null*poly null/create first list of ^ ^ ^ create_node( , ,&poly )create_node( , ,&poly )create_node( , ,&poly )/create second list of ^ ^ create_node( , ,&...
21,574
/function add two polynomial numbers polyadd(poly poly poly)/display resultant list printf("\nadded polynomial")show(poly)return output st number ^ ^ ^ nd number ^ ^ added polynomial ^ ^ ^
21,575
doubly linked list doubly linked list (dllcontains an extra pointertypically called previous pointertogether with next pointer and data which are there in singly linked list following is representation of dll node in language /node of doubly linked list *struct node int datastruct nodenext/pointer to next node in dll s...
21,576
let us call the function that adds at the front of the list is push(the push(must receive pointer to the head pointerbecause push must change the head pointer to point to the new node add node after given node ( steps processwe are given pointer to node as prev_nodeand the new node is inserted after the given node add ...
21,577
because any new node can not be added before null allocate memory for the new nodelet it be called new_node set new_node->data new_data set the previous pointer of this new_node as the previous node of the next_nodenew_node->prev next_node->prev set the previous pointer of the next_node as the new_nodenext_node->prev n...
21,578
circular linked list circular linked list is linked list where all nodes are connected to form circle there is no null at the end circular linked list can be singly circular linked list or doubly circular linked list advantages of circular linked lists any node can be starting point we can traverse the whole list by st...
21,579
struct node *last (struct node*)malloc(sizeof(struct node))/assigning the data last -data data/note list was empty we link single node /to itself last -next lastreturn lastrun on ide insertion at the beginning of the list to insert node at the beginning of the listfollow these step create nodesay make -next last -next ...
21,580
insertion at the end of the list to insert node at the end of the listfollow these step create nodesay make -next last -next last -next last after insertionfunction to insert node in the end of the liststruct node *addend(struct node *lastint dataif (last =nullreturn addtoempty(lastdata)/creating node dynamically
21,581
(struct node *)malloc(sizeof(struct node))/assigning the data temp -data data/adjusting the links temp -next last -nextlast -next templast tempreturn lastinsertion in between the nodes to insert node at the end of the listfollow these step create nodesay search the node after which need to be insertsay that node be mak...
21,582
struct node *addafter(struct node *lastint dataint itemif (last =nullreturn nullstruct node *temp*pp last -next/searching the item do if ( ->data =itemtemp (struct node *)malloc(sizeof(struct node))/assigning the data temp -data data/adjusting the links temp -next -next/adding newly allocated node after -next temp/chec...
21,583
lecture- memory allocationwhenever new node is createdmemory is allocated by the system this memory is taken from list of those memory locations which are free not allocated this list is called avail list similarlywhenever node is deletedthe deleted space becomes reusable and is added to the list of unused space to ava...
21,584
space to availability list the garbage collection may occur when small amount of free space is left in the system or no free space is left in the system or when cpu is idle and has time to do the garbage collection compaction one preferable solution to garbage collection is compaction the process of moving all marked n...
21,585
infix to postfix conversion #include char stack[ ]int top - void push(char xstack[++topxchar pop(if(top =- return - else return stack[top--]int priority(char xif( ='('return if( ='+| ='-'return if( ='*| ='/'return main(char exp[ ]char *exprintf("enter the expression :")scanf("% ",exp) expwhile(* !'\ 'if(isalnum(* )prin...
21,586
while(( pop()!'('printf("% " )else while(priority(stack[top]>priority(* )printf("% ",pop())push(* ) ++while(top !- printf("% ",pop())outputenter the expression : + * abc*enter the expression :( + )* +( -aab+ *da-
21,587
#include int stack[ ] int top - void push(int stack[++topx int pop( return stack[top--] int main( char exp[ ] char * int , , ,num printf("enter the expression :") scanf("% ",exp) exp while(* !'\ ' if(isdigit(* )
21,588
num * push(num) else pop() pop() switch(* case '+' break case '-' break case '*' break
21,589
case '/' break push( ) ++ printf("\nthe result of expression % % \ \ ",exp,pop()) return outputenter the expression : +the result of expression +
21,590
binary tree binary tree consists of finite set of nodes that is either emptyor consists of one specially designated node called the root of the binary treeand the elements of two disjoint binary trees called the left subtree and right subtree of the root note that the definition above is recursivewe have defined binary...
21,591
grandparent and grandchild relations can be defined in similar mannerwe could also extend this terminology further if we wished (designating nodes as cousinsas an uncle or auntetc other tree terms the number of subtrees of node is called the degree of the node in binary treeall nodes have degree or node of degree zero ...
21,592
special forms of binary trees there are few special forms of binary tree worth mentioning if every non-leaf node in binary tree has nonempty left and right subtreesthe tree is termed strictly binary tree orto put it another wayall of the nodes in strictly binary tree are of degree zero or twonever degree one strictly b...
21,593
other strictly binary treean almost complete binary tree with leaves that is not strictly binary has nodes there are two distinct almost complete binary trees with leavesone of which is strictly binary and one of which is not there is only single almost complete binary tree with nodes this tree is strictly binary if an...
21,594
would be stored using this techinque like solinked representation if binary tree is not complete or almost completea better choice for storing it is to use linked representation similar to the linked list structures covered earlier in the semester
21,595
pointer to the root node of the tree (labeled root in the diagram aboveany pointer in the tree structure that does not point to node will normally contain the value null linked tree with nodes will always contain null links
21,596
tree traversaltraversal is process to visit all the nodes of tree and may print their values too becauseall nodes are connected via edges (linkswe always start from the root (headnode that iswe cannot randomly access node in tree there are three ways which we use to traverse tree in-order traversal pre-order traversal ...
21,597
until all nodes are traversed step recursively traverse left subtree step visit root node step recursively traverse right subtree pre-order traversal in this traversal methodthe root node is visited firstthen the left subtree and finally the right subtree we start from aand following pre-order traversalwe first visit i...
21,598
in this traversal methodthe root node is visited lasthence the name first we traverse the left subtreethen the right subtree and finally the root node we start from aand following post-order traversalwe first visit the left subtree is also traversed post-order the process goes on until all the nodes are visited the out...
21,599
avl trees an avl tree is another balanced binary search tree named after their inventorsadelson-velskii and landisthey were the first dynamically balanced trees to be proposed like red-black treesthey are not perfectly balancedbut pairs of subtrees differ in height by at most maintaining an (lognsearch time addition an...