id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
24,700 | data structures using getch()return void insert_val(int valf printf"\nenter the element to be inserted )scanf"% "&val )key val if ht[key=- ht[keyvalelse if key for key ; ; +if ht[ =- ht[ivalbreakfor ; key; +if ht[ =- ht[ivalbreakvoid display(for ( ; ; ++printf"\ % "hti )void search_val(int valflag printf"\nenter the element to be searched :)scanf"% "&val )key val if htkey =val flag else for ( key ; ; ++if(ht[ =valflag key ibreak |
24,701 | if (flag = for ( ; key; ++if (hti =valflag key ibreakif (flag = found= printf("\ the item searched was found at position % !"key )else key - printf"\nthe item searched was not found in the hash table)void delete_val(search_val()if (found== if key !- printf"\nthe element deleted is % "htkey )htkey - output menu insert search delete display exit enter your option enter the element to be inserted : enter your option - - - - - - - - - enter your option collision resolution by chaining in chainingeach location in hash table stores pointer to linked list that contains all the key values that were hashed to that location that islocation in the hash table points to the head of the linked list of all the key values that hashed to howeverif no key value hashes to lthen location in the hash table contains null figure shows how the key values are mapped to location in the hash table and stored in linked list that corresponds to that location |
24,702 | data structures using universe of keys (uk actual keys (kfigure null null null null null keys being hashed to chained hash table operations on chained hash table searching for value in chained hash table is as simple as scanning linked list for an entry with the given key insertion operation appends the key to the end of the linked list pointed by the hashed location deleting key requires searching the list and removing the element chained hash tables with linked lists are widely used due to the simplicity of the algorithms to insertdeleteand search key the code for these algorithms is exactly the same as that for insertingdeletingand searching value in single linked list that we have already studied in while the cost of inserting key in chained hash table is ( )the cost of deleting and searching value is given as (mwhere is the number of elements in the list of that location searching and deleting takes more time because these operations scan the entries of the selected location for the desired key in the worst casesearching value may take running time of ( )where is the number of key values stored in the chained hash table this case arises when all the key values are inserted into the linked list of the same location (of the hash tablein this casethe hash table is ineffective table gives the code to initialize hash table as well as the codes to insertdelete and search value in chained hash table table codes to initializeinsertdeleteand search value in chained hash table struture of the node code to insert value typedef struct node_ht int valuestruct node *next}node/the element is inserted at the beginning of the linked list whose pointer to its head is stored in the location given by (kthe running time of the insert operation is ( )as the new key value is always added as the first element of the list irrespective of the size of the linked list as well as that of the chained hash table *node *insert_valuenode *hash_table[]int valnode *new_nodenew_node (node *)malloc(sizeof(node))new_node value valnew_node next hash_ table[ ( )]hash_table[ ( )new_nodecode to initialize chained hash table /initializes location in the chained hash table the operation takes running time of ( *void initializehashtable (node *hash_table[]int mint ifor( = <= ; ++hash_table[ ]=nullcont |
24,703 | cont code to search value /the element is searched in the linked list whose pointer to its head is stored in the location given by (kif search is successfulthe function returns pointer to the node in the linked listotherwise it returns null the worst case running time of the search operation is given as order of size of the linked list *node *search_value(node *hash_table[]int valnode *ptrptr hash_table[ ( )]while (ptr!=null&(ptr -value !val)ptr ptr -nextif (ptr->value =valreturn ptrelse return nullcode to delete value /to delete node from the linked list whose head is stored at the location given by (kin the hash tablewe need to know the address of the node' predecessor we do this using pointer save the running time complexity of the delete operation is same as that of the search operation because we need to search the predecessor of the node so that the node can be removed without affecting other nodes in the list *void delete_value (node *hash_table[]int valnode *save*ptrsave nullptr hash_table[ ( )]while ((ptr !null&(ptr value !val)save ptrptr ptr nextif (ptr !nullsave next ptr nextfree (ptr)else printf("\ value not found")example insert the keys and in chained hash table of memory locations use (kk mod in this casem= initiallythe hash table can be given asstep key step key ( mod ( mod create linked list for location and store the key value in it as its only node null null null null null null null null create linked list for location and store the key value in it as its only node null null null null null null null null null null null null null null null null |
24,704 | data structures using step key ( mod create linked list for location and store the key value in it as its only node null ( mod null null null null null null null step key ( mod insert at the end of the linked list of location null null null null null key insert at the end of the linked list of location null null null null null step key ( mod insert at the end of the linked list of location step null null null null null null step key step key ( mod ( mod create linked list for location and store create linked list for location and store the the key value in it as its only node key value in it as its only node null null null null null null null null null pros and cons the main advantage of using chained hash table is that it remains effective even when the number of key values to be stored is much higher than the number of locations in the hash table howeverwith the increase in the number of keys to be storedthe performance of chained hash table does degrade gradually (linearlyfor examplea chained hash table with memory locations and , stored keys will give to times less performance as compared to chained hash table with , locations but chained hash table is still times faster than simple hash table the other advantage of using chaining for collision resolution is that its performanceunlike quadratic probingdoes not degrade when the table is more than half full this technique is absolutely free from clustering problems and thus provides an efficient mechanism to handle collisions |
24,705 | howeverchained hash tables inherit the disadvantages of linked lists firstto store key valuethe space overhead of the next pointer in each entry can be significant secondtraversing linked list has poor cache performancemaking the processor cache ineffective bucket hashing in closed hashingall the records are directly stored in the hash table each record with key value is stored in location called its home position the home position is calculated by applying some hash function in case the home position of the record with key is already occupied by another record then the record will be stored in some other location in the hash table this other location will be determined by the technique that is used for resolving collisions once the records are insertedthe same algorithm is again applied to search for specific record one implementation of closed hashing groups the hash table into buckets where slots of the hash table are divided into buckets thereforeeach bucket contains / slots now when new record has to be insertedthe hash function computes the home position if the slot is freethe record is inserted otherwisethe bucket' slots are sequentially searched until an open slot is found in casethe entire bucket is fullthe record is inserted into an overflow bucket the overflow bucket has infinite capacity at the end of the table and is shared by all the buckets an efficient implementation of bucket hashing will be to use hash function that evenly distributes the records amongst the buckets so that very few records have to be inserted in the overflow bucket when searching recordfirst the hash function is used to determine the bucket in which the record can be present then the bucket is sequentially searched to find the desired record if the record is not found and the bucket still has some empty slotsthen it means that the search is complete and the desired record is not present in the hash table howeverif the bucket is full and the record has not been foundthen the overflow bucket is searched until the record is found or all the records in the overflow bucket have been checked obviouslysearching the overflow bucket can be expensive if it has too many records pros and cons of hashing one advantage of hashing is that no extra space is required to store the index as in the case of other data structures in additiona hash table provides fast data access and an added advantage of rapid updates on the other handthe primary drawback of using the hashing technique for inserting and retrieving data values is that it usually lacks locality and sequential retrieval by key this makes insertion and retrieval of data values even more random all the morechoosing an effective hash function is more of an art than science it is not uncommon (in open-addressed hash tablesto create poor hash function applications of hashing hash tables are widely used in situations where enormous amounts of data have to be accessed to quickly search and retrieve information few typical examples where hashing is used are given here hashing is used for database indexing some database management systems store separate file known as the index file when data has to be retrieved from filethe key information is first searched in the appropriate index file which references the exact record location of the data in the database file this key information in the index file is often stored as hashed value in many database systemsfile and directory hashing is used in high-performance file systems such systems use two complementary techniques to improve the performance of file access while |
24,706 | data structures using one of these techniques is caching which saves information in the memorythe other is hashing which makes looking up the file location in the memory much quicker than most other methods hashing technique is used to implement compiler symbol tables in +the compiler uses symbol table to keep record of all the user-defined symbols in +program hashing facilitates the compiler to quickly look up variable names and other attributes associated with symbols hashing is also widely used for internet search engines real world applications of hashing cd databases for cdsit is desirable to have world-wide cd database so that when users put their disk in the cd playerthey get full table of contents on their own computer' screen these tables are not stored on the disks themselvesi the cd does not store any information about the songsrather this information is downloaded from the database the critical issue to solve here is that cds have no id numbers stored on themso how will the computer know which cd has been put in the playerthe only information that can be used is the track lengthand the fact that every cd is different basicallya big number is created from the track lengthsalso known as 'signaturethis signature is used to identify particular cd the signature is value obtained by hashing for examplea number of length of or hexadecimal digits is made upthe number is then sent to the databaseand that database looks for the closest match the reason being that track length may not be measured exactly drivers licenses/insurance cards like our cd exampleeven the driver' license numbers or insurance card numbers are created using hashing from data items that never changedate of birthnameetc sparse matrix sparse matrix is two-dimensional array in which most of the entries contain that isin sparse array there are very few non-zero entries of coursewe can store array as it isbut this would lead to sheer wastage of valuable memory so another possibility is to store the non-zero elements of the spare matrix as elements in array that is by using hashingwe can store two-dimensional array in one-dimensional array there is one-to-one correspondence between the elements in the sparse matrix and the elements in the array this concept is clearly visible in fig if the size of the sparse matrix is ynand there are non-zero entries in itthen from the coordinates ( ,jof matrixwe determine an index in an array by simple calculation thuswe have = ( ,jfor some function hcalled hash function the size of the array is proportional to this is far better from the size of the sparse matrix that required storage proportional to yn for exampleif we have triangular sparse matrix athen an entry [ijcan be mapped to an entry in the array by calculating the index using the hash function (iji( - )/ figure [ sparse matrix table file signatures file signatures provide compact means of identifying files we use functionh[ ]the file signaturewhich is property of the file although we can store files by namesignatures provide compact identity to files since signature depends on the contents of fileif any change is made to the filethen the signature will change in this waythe signature of file can be used as quick verification to see if anyone has altered the fileor if it has lost bit during transmission signatures are widely used for files that store marks of students game boards in the game board for tic-tac-toe or chessa position in game may be stored using hash function |
24,707 | graphics in graphicsa central problem is the storage of objects in scene or view for thiswe organize our data by hashing hashing can be used to make grid of appropriate sizean ordinary vertical-horizontal grid (note that grid is nothing but arrayand there is one-to-one correspondence when we move from array to array sowe store the grid as array as we did in the case of sparse matrices all points that fall in one cell will be stored in the same place if cell contains three pointsthen these three points will be stored in the same entry the mapping from the grid cell to the memory location is done by using hash function the key advantage of this method of storage is fast execution of operations like the nearest neighbour search points to remember hash table is data structure in which keys are mapped to array positions by hash function value stored in hash table can be searched in ( time using hash function which generates an address from the key the storage requirement for hash table is ( )where is the number of keys actually used in hash tablean element with key is stored at index ( )not this means that hash function is used to calculate the index at which the element with key will be stored thusthe process of mapping keys to appropriate locations (or indicesin hash table is called hashing popular hash functions which use numeric keys are division methodmultiplication methodmid square methodand folding method division method divides by and then uses the remainder obtained potential drawback of this method is that consecutive keys map to consecutive hash values multiplication method applies the hash function given as (xi (ka mod mid square method works in two steps firstit finds and then extracts the middle digits of the result folding method works by first dividing the key value into parts knwhere each part has the same number of digits except the last part which may have lesser digits than the other partsand then obtaining the sum of kn the hash value is produced by ignoring the last carryif any collisions occur when hash function maps two different keys to the same location thereforea method used to solve the problem of collisionsalso called collision resolution techniqueis applied the two most popular methods of resolving collisions are(aopen addressing and (bchaining once collision takes placeopen addressing computes new positions using probe sequence and the next record is stored in that position in this technique of collision resolutionall the values are stored in the hash table the hash table will contain two types of values--either sentinel value (for example- or data value open addressing technique can be implemented using linear probingquadratic probingdouble hashingand rehashing in linear probingif value is already stored at location generated by ( )then the following hash function is used to resolve the collisionh(ki[ '(kimod though linear probing enables good memory cachingthe drawback of this algorithm is that it results in primary clustering in quadratic probingif value is already stored at location generated by ( )then the following hash function is used to resolve the collisionh(ki[ '(kc mod quadratic probing eliminates primary clustering and provides good memory caching but it is still liable to secondary clustering in double hashingwe use two hash functions rather than single function the hash function in the case of double hashing can be given ash(ki[ (kih ( )mod the performance of double hashing is very close to the performance of the ideal scheme of uniform hashing it minimizes repeated collisions and the effects of clustering when the hash table becomes nearly fullthe number of collisions increasesthereby degrading the performance of insertion and search operations so in rehashingall the entries in the original hash table are moved to the new hash table which is double the size of the original hash table |
24,708 | data structures using in chainingeach location in hash table stores pointer to linked list that contains all the key values that were hashed to that location while the cost of inserting key in chained hash table is ( )the cost for deleting and searching value is given as ( )where is the number of elements in the list of that location howeverin the worst casesearching for value may take running time of (nexercises review questions define hash table what do you understand by hash functiongive the properties of good hash function how is hash table better than direct access table (array) write short note on the different hash functions give suitable examples calculate hash values of keys using different methods of hashing what is collisionexplain the various techniques to resolve collision which technique do you think is better and why consider hash table with size using linear probinginsert the keys and into the table consider hash table with size using quadratic probinginsert the keys and into the table take and consider hash table with size using double hashinginsert the keys and into the table take mod and mod what is hashinggive its applications alsodiscuss the pros and cons of hashing explain chaining with examples write short notes onlinear probing quadratic probing double hashing multiple-choice questions in hash tablean element with key is stored at index (blog (ch( (dk (ak in any hash functionm should be (aprime number (bcomposite number (ceven number (dodd number in which of the following hash functionsdo consecutive keys map to consecutive hash values(adivision method (bmultiplication method (cfolding method (dmid-square method the process of examining memory locations in hash table is called (ahashing (bcollision (cprobing (daddressing which of the following methods is applied in the berkeley fast file system to allocate free blocks(alinear probing (bquadratic probing (cdouble hashing (drehashing which open addressing technique is free from clustering problems(alinear probing (bquadratic probing (cdouble hashing (drehashing true or false hash table is based on the property of locality of reference binary search takes ( log ntime to execute the storage requirement for hash table is ( )where is the number of keys hashing takes place when two or more keys map to the same memory location good hash function completely eliminates collision should not be too close to exact powers of sentinel value indicates that the location contains valid data linear probing is sensitive to the distribution of input values chained hash table is faster than simple hash table fill in the blanks in hash tablekeys are mapped to array positions by is the process of mapping keys to appropriate locations in hash table in open addressinghash table stores either of two values and when there is no free location in the hash table then occurs more the number of collisionshigher is the number of to find free location which eliminates primary clustering but not secondary clustering eliminates primary clustering but not secondaryclustering |
24,709 | files and their organization learning objective in this we will discuss the basic attributes of file and the different ways in which files can be organized in the secondary memory thenwe will learn about different indexing strategies that allow efficient and faster access to these files introduction nowadaysmost organizations use data collection applications which collect large amounts of data in one form or other for examplewhen we seek admission in collegea lot of data such as our nameaddressphone numberthe course in which we want to seek admissionaggregate of marks obtained in the last examinationand so onare collected similarlyto open bank accountwe need to provide lot of input all these data were traditionally stored on paper documentsbut handling these documents had always been chaotic and difficult task similarlyscientific experiments and satellites also generate enormous amounts of data thereforein order to efficiently analyse all the data that has been collected from different sourcesit has become necessity to store the data in computers in the form of files in computer terminologya file is block of useful data which is available to computer program and is usually stored on persistent storage medium storing file on persistent storage medium like hard disk ensures the availability of the file for future use these daysfiles stored on computers are good alternative to paper documents that were once stored in offices and libraries data hierarchy every file contains data which can be organized in hierarchy to present systematic organization the data hierarchy includes data items such as fieldsrecordsfilesand database these terms are defined below |
24,710 | data field is an elementary unit that stores single fact data field is usually characterized by its type and size for examplestudent' name is data field that stores the name of students this field is of type character and its size can be set to maximum of or characters depending on the requirement record is collection of related data fields which is seen as single unit from the application point of view for examplethe student' record may contain data fields such as nameaddressphone numberroll numbermarks obtainedand so on file is collection of related records for exampleif there are students in classthen there are records all these related records are stored in file similarlywe can have file of all the employees working in an organizationa file of all the customers of companya file of all the suppliersso on and so forth directory stores information of related files directory organizes information so that users can find it easily for exampleconsider fig that shows how multiple related files are stored in student directoy student' personal info file student' academic info file student' fees info file roll_no name address phone no roll_no name course marks grade in sports roll_no name fees lab dues hostel dues library dues figure student directory file attributes every file in computer system is stored in directory each file has list of attributes associated with it that gives the operating system and the application software information about the file and how it is intended to be used software program which needs to access file looks up the directory entry to discern the attributes of that file for exampleif user attempts to write to file that has been marked as read-only filethen the program prints an appropriate message to notify the user that he is trying to write to file that is meant only for reading similarlythere is an attribute called hidden when you execute the dir command in dosthen the files whose hidden attribute is set will not be displayed these attributes are explained in this section file name it is string of characters that stores the name of file file naming conventions vary from one operating system to the other file position it is pointer that points to the position at which the next read/write operation will be performed file structure it indicates whether the file is text file or binary file in the text filethe numbers (integer or floating pointare stored as string of characters binary fileon the other handstores numbers in the same way as they are represented in the main memory |
24,711 | file access method it indicates whether the records in file can be accessed sequentially or randomly in sequential access moderecords are read one by one that isif records of students are stored in the student filethen to read the record of th studentyou have to go through the record of the first students howeverin random accessrecords can be accessed in any order attributes flag file can have six additional attributes attached to it these attributes are usually stored in single bytewith each bit representing specific attribute if particular table attribute flag bit is set to ' then this means that the corresponding attribute is turned on table shows the list of attributes and their position attribute attribute byte in the attribute flag or attribute byte read-only hidden if system file is set as hidden and read-onlythen its attribute system byte can be given as we will discuss all these attributes volume label here in this section note that the directory is treated as special directory file in the operating system soall these attributes are applicable archive to files as well as to directories read-only file marked as read-only cannot be deleted or modified for exampleif an attempt is made to either delete or modify read-only filethen message 'access deniedis displayed on the screen hidden file marked as hidden is not displayed in the directory listing system file marked as system file indicates that it is an important file used by the system and should not be altered or removed from the disk in essenceit is like 'more seriousread-only flag volume label every disk volume is assigned label for identification the label can be assigned at the time of formatting the disk or later through various tools such as the dos command label directory in directory listingthe files and sub-directories of the current directory are differentiated by directory-bit this means that the files that have the directory-bit turned on are actually sub-directories containing one or more files archive the archive bit is used as communication link between programs that modify files and those that are used for backing up files most backup programs allow the user to do an incremental backup incremental backup selects only those files for backup which have been modified since the last backup when the backup program takes the backup of fileor in other wordswhen the program archives the fileit clears the archive bit (sets it to zerosubsequentlyif any program modifies the fileit turns on the archive bit (sets it to thuswhenever the backup program is runit checks the archive bit to know whether the file has been modified since its last run the backup program will archive only those files which were modified text and binary files text filealso known as flat file or an ascii fileis structured as sequence of lines of alphabetnumeralsspecial charactersetc howeverthe data in text filewhether numeric or non-numericis stored using its corresponding ascii code the end of text file is often denoted by placing special charactercalled an end-of-file markerafter the last line in the text file binary file contains any type of data encoded in binary form for computer storage and processing purposes binary file can contain text that is not broken up into lines binary file stores data in format that is similar to the format in which the data is stored in the main memory |
24,712 | data structures using thereforea binary file is not readable by humans and it is up to the program reading the file to make sense of the data that is stored in the binary file and convert it into something meaningful ( fixed length of recordbinary files contain formatting information that only certain applications or processors can understand it is possible for humans to read text files which contain only ascii textwhile binary files must be run on an appropriate software or processor so that the software or processor can transform the data in order to make it readable for exampleonly microsoft word can interpret the formatting information in word document although text files can be manipulated by any text editorthey do not provide efficient storage in contrastbinary files provide efficient storage of databut they can be read only through an appropriate program basic file operations the basic operations that can be performed on file are given in fig file operations creation insertion updation modification retrieval deletion inquiry report generation maintenance restructuring reorganization figure file operations creating file file is created by specifying its name and mode then the file is opened for writing records that are read from an input device once all the records have been written into the filethe file is closed the file is now available for future read/write operations by any program that has been designed to use it in some way or the other updating file updating file means changing the contents of the file to reflect current picture of reality file can be updated in the following waysinserting new record in the file for exampleif new student joins the coursewe need to add his record to the student file deleting an existing record for exampleif student quits course in the middle of the sessionhis record has to be deleted from the student file modifying an existing record for exampleif the name of student was spelt incorrectlythen correcting the name will be modification of the existing record retrieving from file it means extracting useful data from given file information can be retrieved from file either for an inquiry or for report generation an inquiry for some data retrieves low volume of datawhile report generation may retrieve large volume of data from the file maintaining file it involves restructuring or re-organizing the file to improve the performance of the programs that access this file restructuring file keeps the file organization unchanged and changes only the structural aspects of the file (for examplechanging the field width or adding/deleting fieldson |
24,713 | the other handfile reorganization may involve changing the entire organization of the file we will discuss file organization in detail in the next section file organization we know that file is collection of related records the main issue in file management is the way in which the records are organized inside the file because it has significant effect on the system performance organization of records means the logical arrangement of records in the file and not the physical layout of the file as stored on storage media since choosing an appropriate file organization is design decisionit must be done keeping the priority of achieving good performance with respect to the most likely usage of the file thereforethe following considerations should be kept in mind before selecting an appropriate file organization methodrapid access to one or more records ease of inserting/updating/deleting one or more records without disrupting the speed of accessing record(sefficient storage of records using redundancy to ensure data integrity although one may find that these requirements are in contradiction with each otherit is the designer' job to find good compromise among them to get an adequate solution for the problem at hand for examplethe ease of addition of records can be compromised to get fast access to data in this sectionwe will discuss some of the techniques that are commonly used for file organization sequential organization sequentially organized file stores the records in the order in which they were entered that isthe first record that was entered is written as the first record in the filethe second record entered is written as the second record in the fileand so on as resultnew records are added only at the end of the file sequential files can be read only sequentiallystarting with the first record in the file sequential file organization is the most basic way to organize large collection of records in file figure shows records numbered from to - stored in sequential file once we store the records in filewe cannot make any changes to the records we cannot even delete the records from sequential file in case we need to delete or beginning record update one or more recordswe have to replace the records by creating of file new file record in sequential file organizationall the records have the same size and the same field formatand every field has fixed size the records are sorted based on the value of one field or combination of two or more record fields this field is known as the key each key uniquely identifies record + record in file thusevery record has different value for the key field records can be sorted in either ascending or descending order sequential files are generally used to generate reports or to perform sequential reading of large amount of data which some programs need record - to do such as payroll processing of all the employees of an organization record - end of file sequential files can be easily stored on both disks and tapes table summarizes the featuresadvantagesand disadvantages of sequential figure sequential file file organization organization |
24,714 | data structures using table sequential file organization features advantages disadvantages records are written in the order in which they are entered records are read and written sequentially deletion or updation of one or more records calls for replacing the original file with new file that contains the desired changes records have the same size and the same field format records are sorted on key value generally used for report generation or sequential reading simple and easy to handle no extra overheads involved sequential files can be stored on magnetic disks as well as magnetic tapes well suited for batchoriented applications records can be read only th sequentially if record has to be readthen all the - records must be read does not support update operation new file has to be created and the original file has to be replaced with the new file that contains the desired changes cannot be used for interactive applications relative file organization relative file organization provides an effective way to access individual records directly in relative file organizationrecords are ordered by their relative key it means the record number represents the location of the record relative to the beginning of the file the record numbers range from to - where is the number of records in the file for examplethe record with record number is the first record in the file the records in relative file are of fixed length thereforein relative filesrecords are organized in ascending relative record number relative file can be thought of as single dimension table stored on diskin which the relative record number is the index into the table relative files can be used for both random as well as sequential access for sequential accessrecords are simply read one after another relative files provide support for only one keythat isthe relative record number this key must be numeric and must take value between and the current highest relative record number - this means that enough space must be allocated for the file to contain the records with relative record numbers between and the highest record number - for exampleif the highest relative record number is , then space must be allocated to store , records in the file figure shows schematic representation of relative file which has been allocated enough space to store records although it has space to accommodate recordsnot all the locations are occupied the locations marked as free are yet to store records in them thereforeevery location in the table either stores relative record records stored record or is marked as free in memory number relative file organization provides random access by directly record jumping to the record which has to be accessed if the records record are of fixed length and we know the base address of the file and the length of the recordthen any record can be accessed using free the following formula free record free record figure relative file organization address of ith record base_address ( - record_length note that the base address of the file refers to the starting address of the file we took - in the formula because record numbers start from rather than consider the base address of file is and each record occupies bytesthen the address of the th record can be given |
24,715 | as ( - table summarizes the featuresadvantagesand disadvantages of relative file organization table relative file organization features advantages disadvantages provides an effective way to access individual records the record number represents the location of the record relative to the beginning of the file records in relative file are of fixed length relative files can be used for both random as well as sequential access every location in the table either stores record or is marked as free ease of processing if the relative record number of the record that has to be accessed is knownthen the record can be accessed instantaneously random access of records makes access to relative files fast allows deletions and updations in the same file provides random as well as sequential access of records with low overhead new records can be easily added in the free locations based on the relative record number of the record to be inserted well suited for interactive applications use of relative files is restricted to disk devices records can be of fixed length only for random access of recordsthe relative record number must be known in advance indexed sequential file organization indexed sequential file organization stores data for fast retrieval the records in an indexed sequential file are of fixed length and every record is uniquely identified by key field we maintain table known as the index table which stores the record number and the address of all the records that is for every filewe have an index table this type of file organization is called as indexed sequential file organization because physically the records may be stored anywherebut the index table stores the address of those records the ith entry in the index table points to the ith record of the file initiallywhen the file is createdeach entry in the index table contains null when the ith record of the file is writtenfree space is obtained from the free space manager and its address is stored in the ith location of the index table record address of nowif one has to read the th recordthen there is no number the record record need to access the first three records address of the th record can be obtained from the index table and the record record can be straightaway read from the specified address ( record in our exampleconceptuallythe index sequential file organization can be visualized as shown in fig record null an indexed sequential file uses the concept of both sequential as well as relative files while the index table is null read sequentially to find the address of the desired recorda null direct access is made to the address of the specified record null in order to access it randomly null indexed sequential files perform well in situations where figure indexed sequential file organization sequential access as well as random access is made to |
24,716 | the data indexed sequential files can be stored only on devices that support random accessfor examplemagnetic disks for exampletake an example of college where the details of students are stored in an indexed sequential file this file can be accessed in two wayssequentially--to print the aggregate marks obtained by each student in particular course or randomly--to modify the name of particular student table summarizes the featuresadvantagesand disadvantages of indexed sequential file organization table indexed sequential file organization features advantages disadvantages provides fast data retrieval records are of fixed length index table stores the address of the records in the file the ith entry in the index table points to the ith record of the file while the index table is read sequentially to find the address of the desired recorda direct access is made to the address of the specified record in order to access it randomly indexed sequential files perform well in situations where sequential access as well as random access is made to the data the key improvement is that the indices are small and can be searched quicklyallowing the database to access only the records it needs supports applications that require both batch and interactive processing records can be accessed sequentially as well as randomly updates the records in the same file indexed sequential files can be stored only on disks needs extra space and overhead to store indices handling these files is more complicated than handling sequential files supports only fixed length records indexing an index for file can be compared with catalogue in library like library has card catalogues based on authorssubjectsor titlesa file can also have one or more indices indexed sequential files are very efficient to usebut in real-world applicationsthese files are very large and single file may contain millions of records thereforein such situationswe require more sophisticated indexing technique there are several indexing techniques and each technique works well for particular application for particular situation at handwe analyse the indexing technique based on factors such as access typeaccess timeinsertion timedeletion timeand space overhead involved there are two kinds of indicesordered indices that are sorted based on one or more key values hash indices that are based on the values generated by applying hash function ordered indices indices are used to provide fast random access to records as stated abovea file may have multiple indices based on different key fields an index of file may be primary index or secondary index primary index in sequentially ordered filethe index whose search key specifies the sequential order of the file is defined as the primary index for examplesuppose records of students are stored in student file in sequential order starting from roll number to roll number nowif we want to search |
24,717 | record forsayroll number then the student' roll number is the primary index indexed sequential files are common example where primary index is associated with the file secondary index an index whose search key specifies an order different from the sequential order of the file is called as the secondary index for exampleif the record of student is searched by his namethen the name is secondary index secondary indices are used to improve the performance of queries on non-primary keys dense and sparse indices in dense indexthe index table stores the address of every record in the file howeverin sparse indexthe index table stores the address of only some of the records in the file although sparse indices are easy to fit in the main memorya dense index would be more efficient to use than sparse index if it fits in the memory figure shows dense index and sparse index for an indexed sequential file record pointer to number record record pointer to next record record pointer to number record record record record record record record record record record record record record record (adense index pointer to next record (bsparse index figure dense index and sparse index note that the records need not be stored in consecutive memory locations the pointer to the next record stores the address of the next record by looking at the dense indexit can be concluded directly whether the record exists in the file or not this is not the case in sparse index in sparse indexto locate recordwe first find an entry in the index table with the largest search key value that is either less than or equal to the search key value of the desired record thenwe start at that record pointed to by that entry in the index table and then proceed searching the record using the sequential pointers in the fileuntil the desired record is obtained for exampleif we need to access record number then record number is the largest key value that is less than so jump to the record pointed by record number and move along the sequential pointer to reach record number thus we see that sparse index takes more time to find record with the given key dense indices are faster to usewhile sparse indices require less space and impose less maintenance for insertions and deletions cylinder surface indexing cylinder surface indexing is very simple technique used only for the primary key index of sequentially ordered file in sequentially ordered filethe records are stored sequentially in the increasing order of the primary key the index file will contain two fields--cylinder index and several surface indices generallythere are multiple cylindersand each cylinder has multiple surfaces if the file needs cylinders for storage then the cylinder index will contain entries |
24,718 | data structures using each cylinder will have an entry corresponding to the largest key value into that cylinder if the disk has usable surfacesthen each of the surface indices will have entries thereforethe ith entry in the surface index for cylinder is the largest key value on the jth track of the ith surface hencethe total number of surface index entries is the physical and logical organization of disk is shown in fig note the number of cylinders in disk is only few hundred and the cylinder index occupies only one track when record with particular key value has to be searchedthen the following steps are performedfirst the cylinder index of the file is read into memory secondthe cylinder index is searched to determine which cylinder holds the desired record for thiseither the binary search technique can be used or the cylinder index can be made to store an array of pointers to the starting of individual key values in either case the search will take (log mtime after the cylinder index is searchedappropriate cylinder is determined depending on the cylinderthe surface index corresponding to the cylinder is then retrieved from the disk since the number of surfaces on disk is very smalllinear search can be used to determine surface index of the record once the cylinder and the surface are determinedthe corresponding track is read and searched for the record with the desired key hencethe total number of disk accesses is three--firstfor accessing the cylinder indexsecond for accessing the surface indexand third for getting the track address howeverif track sizes are very large then it may not be good idea to read the whole track at once in surface such situationswe can also include sector multiple addresses but this would add an extra level tracks of indexing andthereforethe number of one surface cylinder accesses needed to retrieve record will then surface become four in addition to thiswhen the file extends over several disksa disk index surface will also be added surface the cylinder surface indexing method of maintaining file and index is referred surface to as indexed sequential access method sectors (isamthis technique is the most popular and simplest file organization in use for figure physical and logical organization of disk single key values but with files that contain multiple keysit is not possible to use this index organization for the remaining keys multi-level indices in real-world applicationswe have very large files that may contain millions of records for such filesa simple indexing technique will not suffice in such situationwe use multi-level indices to understand this conceptconsider file that has , records if we use simple indexingthen we need an index table that can contain at least , entries to point to , records if |
24,719 | each entry in the index table occupies bytesthen we need an index table of bytes bytes finding such big space consecutively is not always easy soa better scheme is to index the index table figure shows two-level multi-indexing we can continue further by having three-level indexing and so on but practicallywe use two-level indexing note that two and higher-level indexing must always be sparseotherwise multi-level indexing will lose its effectiveness in the figurethe main index table stores pointers to three inner index tables the inner index tables are sparse index tables that in turn store pointers to the records record number pointer to record record number pointer to record record number record number pointer to record records pointer to record figure multi-level indices inverted indices inverted files are commonly used in document retrieval systems for large textual databases an inverted file reorganizes the structure of an existing data file in order to provide fast access to all records having one field falling within the set limits for exampleinverted files are widely used by bibliographic databases that may store author namestitle wordsjournal namesetc when term or keyword specified in the inverted file is identifiedthe record number is given and set of records corresponding to the search criteria are created thusfor each keywordan inverted file contains an inverted list that stores list of pointers to all occurrences of that term in the main text thereforegiven keywordthe addresses of all the documents containing that keyword can easily be located there are two main variants of inverted indicesa record-level inverted index (also known as inverted file index or inverted filestores list of references to documents for each word word-level inverted index (also known as full inverted index or inverted listin addition to list of references to documents for each word also contains the positions of each word within document although this technique needs more time and spaceit offers more functionality (like phrase searches |
24,720 | data structures using thereforethe inverted file system consists of an index file in addition to document file (also known as text fileit is this index file that contains all the keywords which may be used as search terms for each keywordan address or reference to each location in the document where that word occurs is stored there is no restriction on the number of pointers associated with each word for efficiently retrieving word from the index filethe keywords are sorted in specific order (usually alphabeticallyhoweverthe main drawback of this structure is that when new words are added to the documents or text filesthe whole file must be reorganized thereforea better alternative is to use -trees -tree indices database is defined as collection of data organized in fashion that facilitates updatingretrievingand managing the data (that may include any itemsuch as namesaddressespicturesand numbersmost organizations maintain databases for their business operations for examplean airline reservation system maintains database of flightscustomersand tickets issued university maintains database of all its students these real-world databases may contain millions of records that may occupy gigabytes of storage space for database to be usefulit must support fast retrieval and storage of data since it is impractical to maintain the entire database in the memoryb-trees are used to index the data in order to provide fast access for examplesearching value in an un-indexed and unsorted database containing key values may take running time of (nin the worst casebut if the same database is indexed with -treethe search operation will run in (log ntime majority of the database management systems use the -tree index technique as the default indexing method this technique supersedes other techniques of creating indicesmainly due to its data retrieval speedease of maintenanceand simplicity figure shows -tree index - - - - - - - - - - - - amar david ben emily gauri henry charan fred inder dorsy-address emily-address fred-address figure -tree index james mercy parul simi kim lorleen naresh quinn rusty ted umesh omar pointers to records vimi yasin wills zubir |
24,721 | it forms tree structure with the root at the top the index consists of -tree (balanced treestructure based on the values of the indexed column in this examplethe indexed column is name and the -tree is created using all the existing names that are the values of the indexed column the upper blocks of the tree contain index data pointing to the next lower blockthus forming hierarchical structure the lowest level blocksalso known as leaf blockscontain pointers to the data rows stored in the table if table has column that has many unique valuesthen the selectivity of that column is said to be high -tree indices are most suitable for highly selective columnsbut it causes sharp increase in the size when the indices contain concatenation of multiple columns the -tree structure has the following advantagessince the leaf nodes of -tree are at the same depthretrieval of any record from anywhere in the index takes approximately the same time -trees improve the performance of wide range of queries that either search value having an exact match or for value within specified range -trees provide fast and efficient algorithms to insertupdateand delete records that maintain the key order -trees perform well for small as well as large tables their performance does not degrade as the size of table grows -trees optimize costly disk access hashed indices in the last we discussed hashing in detail the same concept of hashing can be used to create hashed indices so farwe have studied that hashing is used to compute the address of record by using hash function on the search key value if at any point of timethe hashed values map to the same addressthen collision occurs and schemes to resolve these collisions are applied to generate new address choosing good hash function is critical to the success of this technique by good hash functionwe mean two things firsta good hash functionirrespective of the number of search keysgives an average-case lookup that is small constant secondthe function distributes records uniformly and randomly among the bucketswhere bucket is defined as unit of one or more records (typically disk blockcorrespondinglythe worst hash function is one that maps all the keys to the same bucket howeverthe drawback of using hashed indices includesthough the number of buckets is fixedthe number of files may grow with time if the number of buckets is too largestorage space is wasted if the number of buckets is too smallthere may be too many collisions it is recommended to set the number of buckets to twice the number of the search key values in the file this gives good space-performance tradeoff hashed file organization uses hashed indices hashing is used to calculate the address of disk block where the desired record is stored if is the set of all search key values and is the set of all bucket addressesthen hash function maps to we can perform the following operations in hashed file organization insertion to insert record that has ki as its search valueuse the hash function (kito compute the address of the bucket for that record if the bucket is freestore the record else use chaining to store the record |
24,722 | data structures using search to search record having the key value kiuse (kito compute the address of the bucket where the record is stored the bucket may contain one or several recordsso check for every record in the bucket (by comparing ki with the key of every recordto finally retrieve the desired record with the given key value deletion to delete record with key value kiuse (kito compute the address of the bucket where the record is stored the bucket may contain one or several records so check for every record in the bucket (by comparing ki with the key of every recordthen delete the record as we delete node from linear linked list we have already studied how to delete record from chained hash table in note that in hashed file organizationthe secondary indices need to be organized using hashing points to remember file is block of useful information which is available to computer program and is usually stored on persistent storage medium every file contains data this data can be organized in hierarchy to present systematic organization the data hierarchy includes data items such as fieldsrecordsfilesand database data field is an elementary unit that stores single fact record is collection of related data fields which is seen as single unit from the application point of view file is collection of related records directory is collection of related files database is defined as collection of data organized in fashion that facilitates updatingretrievingand managing the data there are two types of computer files--text files and binary files text file is structured as sequence of lines of alphabetnumbersspecial charactersetc howeverthe data in text file is stored using its corresponding ascii code whereas in binary filesthe data is stored in binary formi in the format it is stored in the memory each file has list of attributes associated with it which can have one of two states--on or off these attributes areread-onlyhiddensystemvolume labelarchiveand directory file marked as read-only cannot be deleted or modified hidden file is not displayed in the directory listing system file is used by the system and should not be altered or removed from the disk the archive bit is useful for communication between programs that modify files and programs that are used for backing up files file that has the directory bit turned on is actually sub-directory containing one or more files file organization means the logical arrangement of records in the file files can be organized as sequentialrelativeor index sequential sequentially organized file stores records in the order in which they were entered in relative file organizationrecords in file are ordered by their relative key relative files can be used for both random access as well as sequential access of data in an indexed sequential fileevery record is uniquely identified by key field we maintain table known as the index table that stores record number and the address of the record in the file there are several indexing techniquesand each technique works well for particular application in dense indexindex table stores the address of every record in the file howeverin sparse indexindex table stores address of only some of the records in the file cylinder surface indexing is very simple technique which is used only for the primary key index of sequentially ordered file in multi-level indexingwe can create an index to the index itself the original index is called the firstlevel index and the index to the index is called the second-level index |
24,723 | inverted files are frequently used indexing technique in document retrieval systems for large textual databases an inverted file reorganizes the structure of an existing data file in order to provide fast access to all records having one field falling within set limits majority of the database management systems use -tree indexing technique the index consists of hierarchical structure with upper blocks containing indices pointing to the lower blocks and lowest level blocks containing pointers to the data records hashed file organization uses hashed indices hashing is used to calculate the address of disk block where the desired record is stored if is the set of all search key values and is the set of bucket addressesthen hash function maps to exercises review questions why do we need files explain the terms fieldrecordfile organizationkeyand index define file explain all the file attributes how is archive attribute useful differentiate between binary file and text file explain the basic file operations what do you understand by the term file organizationbriefly summarize the different file organizations that are widely used today write brief note on indexing differentiate between sparse index and dense index explain the significance of multi-level indexing with an appropriate example what are inverted fileswhy are they needed give the merits and demerits of -tree index multiple-choice questions which of the following flags is cleared when file is backed up(aread-only (bsystem (chidden (darchive which is an important file used by the system and should not be altered or removed from the disk(ahidden file (barchived file (csystem file (dread-only file the data hierarchy can be given as (afieldsrecordsfiles and database (brecordsfilesfields and database (cdatabasefilesrecords and fields (dfieldsrecordsdatabaseand files which of the following indexing techniques is used in document retrieval systems for large databases(ainverted index (bmulti-level indices (chashed indices (db-tree index true or false when backup program archives the fileit sets the archive bit to one in text filedata is stored using ascii codes binary file is more efficient than text file maintenance of file involves re-structuring or re-organization of the file relative files can be used for both random access of data as well as sequential access in sparse indexindex table stores the address of every record in the file higher level indexing must always be sparse -tree indices are most suitable for highly selective columns fill in the blanks is block of useful information data field is usually characterized by its and is collection of related data fields |
24,724 | data structures using is pointer that points to the position at which next read/write operation will be performed indicates whether the file is text file or binary file index table stores and of the record in the file in sequentially ordered file the index whose search key specifies the sequential order of the file is defined as the index files are frequently used indexing technique in document retrieval systems for large textual databases is collection of data organized in fashion that facilitates updatingretrievingand managing the data |
24,725 | memory allocation in programs supports three kinds of memory allocation through the variables in programsstatic allocation when we declare static or global variablestatic allocation is done for the variable each static or global variable is allocated fixed size of memory space the number of bytes reserved for the variable cannot change during execution of the program automatic allocation when we declare an automatic variablesuch as function argument or local variableautomatic memory allocation is done the space for an automatic variable is allocated when the compound statement containing the declaration is enteredand is freed when it exits from compound statement dynamic allocation third important kind of memory allocation is known as dynamic allocation in the following sections we will read about dynamic memory allocation using pointers memory usage before jumping into dynamic memory allocationlet us first understand how memory is used conceptuallymemory is divided into two parts--program memory and data memory (fig memory program memory main(figure other function data memory global stack heap memory usage the program memory consists of memory used for the main(and other called functions in the programwhereas data memory consists of memory needed for permanent definitions such as global datalocal dataconstantsand dynamic memory data the way in which handles the memory requirements is function of the operating system and the compiler when program is being executedits main(and all other functions are always kept in the memory howeverthe local variables of the function are available in the memory only when they are active when we studied recursive functionswe have seen that the system stack is used to store single copy of the function and multiple copies of the local variables |
24,726 | apart from the stackwe also have memory pool known as heap heap memory is unused memory allocated to the program and available to be assigned during its execution when we dynamically allocate memory for variablesheap acts as memory pool from which memory is allocated to those variables howeverthis is just conceptual view of memory and implementation of the memory is entirely in the hands of system designers dynamic memory allocation the process of allocating memory to the variables during execution of the program or at run time is known as dynamic memory allocation language has four library routines which allow this function till now whenever we needed an array we had declared static array of fixed size as int arr[ ]when this statement is executedconsecutive space for integers is allocated it is not uncommon that we may be using only or of the allocated spacethereby wasting rest of the space to overcome this problem and to utilize the memory efficientlyc language provides mechanism of dynamically allocating memory so that only the amount of memory that is actually required is reserved we reserve space only at the run time for the variables that are actually required dynamic memory allocation gives best performance in situations in which we do not know memory requirements in advance provides four library routines to automatically allocate memory at the run time these routines are shown in table table memory allocation/de-allocation functions function task malloc(allocates memory and returns pointer to the first byte of allocated space calloc(allocates space for an array of elementsinitializes them to zero and returns pointer to the memory free(frees previously allocated memory realloc(alters the size of previously allocated memory when we have to dynamically allocate memory for variables in our programs then pointers are the only way to go when we use malloc(for dynamic memory allocationthen you need to manage the memory allocated for variables yourself memory allocations process in computer sciencethe free memory region is called heap the size of heap is not constant as it keeps changing when the program is executed in the course of program executionsome new variables are created and some variables cease to exist when the block in which they were declared is exited for this reason it is not uncommon to encounter memory overflow problems during dynamic allocation process when an overflow condition occursthe memory allocation functions mentioned above will return null pointer allocating block of memory let us see how memory is allocated using the malloc()function malloc is declared in so we include this header file in any program that calls malloc the malloc function reserves block |
24,727 | of memory of specified size and returns pointer of type void this means that we can assign it to any type of pointer the general syntax of malloc(is ptr =(cast-type*)malloc(byte-size)where ptr is pointer of type cast-type malloc(returns pointer (of cast typeto an area of memory with size byte-size for examplearr=(int*)malloc( *sizeof(int))this statement is used to dynamically allocate memory equivalent to times the area of int bytes on successful execution of the statement the space is reserved and the address of the first byte of memory allocated is assigned to the pointer arr of type int programming tip calloc(function is another function that reserves memory at the run time it is normally used to request multiple blocks of storage each to use dynamic memory allocation functionsyou must of the same size and then sets all bytes to zero calloc(stands for include the header file stdlib contiguous memory allocation and is primarily used to allocate memory for arrays the syntax of calloc(can be given asptr=(cast-type*calloc( ,elem-size)the above statement allocates contiguous space for blocks each of size elem-size bytes the only difference between malloc(and calloc(is that when we use calloc()all bytes are initialized to zero calloc(returns pointer to the first byte of the allocated region when we allocate memory using malloc(or calloc() null pointer will be returned if there is not enough space in the system to allocate null pointerpoints definitely nowhere it is not pointer markerthereforeit is not pointer you can use thuswhenever you allocate memory using malloc(or calloc()you must check the returned pointer before using it if the program receives null pointerit should at the very least print an error message and exitor perhaps figure out some way of proceeding without the memory it asked for but in any casethe program cannot go on to use the null pointer it got back from malloc()/calloc( call to mallocwith an error checktypically looks something like thisint *ip malloc( sizeof(int))if(ip =nullprintf("\ memory could not be allocated")returnwrite program to read and display values of an integer array allocate space dynamically for the array #include #include int main(int inint *arrprintf("\ enter the number of elements ")scanf("% "& )arr (int *)malloc( sizeof(int))if(arr =nullprintf(\ memory allocation failed")exit( ) |
24,728 | data structures using for( ; ; ++printf("\ enter the value % of the array" )scanf("% "&arr[ ])printf("\ the array contains \ ")for( ; ; ++printf("% "arr[ ])return now let us also see how we can allocate memory using the calloc function the calloc(function accepts two parameters--num and sizewhere num is the number of elements to be allocated and size is the size of elements the following program demonstrates the use of calloc(to dynamically allocate space for an integer array #include #include int main (int ,nint *arrprintf ("\ enter the number of elements")scanf("% ",& )arr (int*calloc( ,sizeof(int))if (arr==nullexit ( )printf("\ enter the % values to be stored in the array" )for ( ni++scanf ("% ",&arr[ ])printf ("\ you have entered")for( ni++printf ("% ",arr[ ])free(arr)return releasing the used space when variable is allocated space during the compile timethen the memory used by that variable is automatically released by the system in accordance with its storage class but when we dynamically allocate memory then it is our responsibility to release the space when it is not required this is even more important when the storage space is limited thereforeif we no longer need the data stored in particular block of memory and we do not intend to use that block for storing any other informationthen as good programming practice we must release that block of memory for future useusing the free function the general syntax of the free()function isfree(ptr)where ptr is pointer that has been created by using malloc(or calloc(when memory is deallocated using free()it is returned back to the free list within the heap to alter the size of allocated memory at times the memory allocated by using calloc(or malloc(might be insufficient or in excess in both the situations we can always use realloc(to change the memory size already allocated by calloc(and malloc(this process is called reallocation of memory the general syntax for realloc(can be given as |
24,729 | ptr realloc(ptr,newsize)the function realloc(allocates new memory space of size specified by newsize to the pointer variable ptr it returns pointer to the first byte of the memory block the allocated new block may be or may not be at the same region thuswe see that realloc(takes two arguments the first is the pointer referencing the memory and the second is the total number of bytes you want to reallocate if you pass zero as the second argumentit will be equivalent to calling free(like malloc(and calloc()realloc returns void pointer if successfulelse null pointer is returned if realloc(was able to make the old block of memory biggerit returns the same pointer otherwiseif realloc(has to go elsewhere to get enough contiguous memory then it returns pointer to the new memoryafter copying your old data there howeverif realloc(cannot find enough memory to satisfy the new request at allit returns null pointer so again you must check before using that the pointer returned by the realloc(is not null pointer /*example program for reallocation*#include #include #define null int main(char *strstr (char *)malloc( )if(str==nullprintf("\ memory could not be allocated")exit( )strcpy(str,"hi")printf("\ str % "str)/*reallocation*str (char *)realloc(str, )if(str==nullprintf("\ memory could not be reallocated")exit( )printf("\ str size modified\ ")printf("\ str % \ "str)strcpy(str,"hi there")printf("\ str % "str)/*freeing memory*free(str)return note with realloc()you can allocate more bytes without losing your data dynamically allocating - array we have seen how malloc(can be used to allocate block of memory which can simulate an array now we can extend our understanding further to do the same to simulate multidimensional arrays if we are not sure of the number of columns that the array will havethen we will first allocate memory for each row by calling malloc each row will then be represented by pointer look at the code below which illustrates this concept #include #include |
24,730 | data structures using int main(int **arrijrowscolsprintf("\ enter the number of rows and columns in the array")scanf("% % "rowscols)arr (int **)malloc(rows sizeof(int *))if(arr =nullprintf("\ memory could not be allocated")exit(- )for( = <rowsi++arr[ (int *)malloc(cols sizeof(int))if(arr[ =nullprintf("\ memory allocation failed")exit(- )printf("\ enter the values of the array")for( rowsi++for( colsj++scanf("% "&arr[ ][ ])printf("\ the array is as follows")for( rowsi++for( colsj++printf("% "arr[ ][ ])for( rowsi++free(arr[ ])free(arr)return herearr is pointer-to-pointer-to-intat the first level as it points to block of pointersone for each row we first allocate space for rows in the array the space allocated to each row is big enough to hold pointer-to-intor int if we successfully allocate itthen this space will be filled with pointers to columns (number of intsthis can be better understood from fig arr row column figure memory allocation of two-dimensional array |
24,731 | once the memory is allocated for the two-dimensional arraywe can use subscripts to access its elements when we writearr[ ][ ]it means we are looking for the ith pointer pointed to by arrand then for the jth int pointed to by that inner pointer when we have to pass such an array to functionthen the prototype of the function will be written as func(int **arrint rowsint cols)in the above declarationfunc accepts pointer-to-pointer-to-int and the dimensions of the arrays as parametersso that it will know how many rows and columns are there |
24,732 | garbage collection garbage collection is dynamic approach used for automatic memory management to reduce the memory leak problems the garbage collection process identifies unused memory blocks and reallocates that storage for reuse garbage collection is implemented using the following approachesmark-and-sweep in this approach when memory runs outthe garbage collection process locates all accessible memory and then reclaims the available memory reference counting the garbage collection process here maintains reference count of referencing number for each allocated object when the memory count becomes zerothe object is marked as garbage and then destroyed by freeing its memory the freed memory is finally returned to the memory heap copy collection the garbage collection process maintains two memory partitions when the first partition is fullthe garbage collection process identifies all accessible data structures and copies them to the second partition then it compacts memory to allow continuous free memory note some programming languages like javac#netetc have built-in garbage collection process to self-manage memory leak problem advantages of garbage collection garbage collection frees the programmer from manually dealing with memory de-allocationthereby eliminating or substantially reducing following types of programming bugsdangling pointer bugs are often encountered when the memory allocated to variable (or an objectis freed but there are still pointers pointing to it if such pointers are de-referenced especially when that memory is re-allocated to another variable or objectthen results are simply unpredictable double free bugs occur when the program tries to free piece of memory that has already been freed it may be case that the freed memory has now been re-allocated to some other variable or object of the same or different program in such casethe program will again give erroneous results memory leaks occur when program is unable to free memory occupied by objects that have become unreachable garbage collection also helps in efficient implementation of persistent data structures |
24,733 | disadvantages of garbage collection the typical disadvantages of garbage collection process includegarbage collection consumes computing resources to decide which piece of memory must be freed this information may already be available with the programmer the time at which the garbage collection process will be executed is unpredictable which may lead to stalls scattered throughout session this is unacceptable in real-time environmentstransaction processingor in interactive programs although incrementalconcurrentand real-time garbage collectors solve this problem but with some or the other trade-off some of the bugs addressed by garbage collection can have certain security implications requirements for automatic garbage collection an effective and efficient garbage collection process must have the following propertiesmust identify garbage the object or variable identified as garbage must actually be garbage must have less overhead during garbage collectionthe execution of the program is temporarily delayed this delay must be minimum |
24,734 | backtracking backtracking is general algorithm that finds all or some solutions to any computational problem that incrementally builds candidates to the solutions at each stepwhile the valid candidates to the solution are extendedthe other candidates are discarded that iseach partial candidate is immediately abandoned after it is determined that cannot be possible and valid solution to the problem hencethe namebacktrack the concept of backtracking is applicable only to problems that support partial candidate solutions and relatively quick test to determine if the partial candidate solution can be completed to valid solution backtracking is extensively used to solve constraint satisfaction problems such as followingpuzzles like sudokueight queen' problemcrosswordsverbal arithmeticsolitaire combinational optimization problem like parsing and knapsack problem logic programming languages that internally use backtracking include iconplanner and prolog diff which is version comparing engine for the mediawiki software backtracking is said to be meta-heuristic algorithm (in contrast to specific algorithmthat is guaranteed to find all solutions to finite problem in bounded amount of time the term meta-heuristic implies that the algorithm works based on user-given procedures that define the problem to be solvedthe nature of the partial candidatesand how they are extended into complete candidates conceptualizing the backtracking process as potential search treethe partial candidates of the solution can be viewed as the nodes of the tree each partial candidate has child nodes that represent the candidates that differ from it by single extension step of coursethe leaf nodes are the partial candidates that cannot be extended further the backtracking algorithm recursively traverses the search tree in depth-first order (starting from the root nodeat each node cthe algorithm checks if can be completed to valid solution if it cannot be completedthen the entire sub-tree rooted at is pruned howeverif there is possibility that may lead to valid solution then the algorithm first checks if itself is valid solution if yesthen the algorithm declares as the valid solution otherwise it recursively enumerates all sub-trees of note the tests to determine the valid solution and children of each node are all defined by user-given procedures |
24,735 | look at the search tree given below root solution solution (badsolution (badsolution solution (badsolution (goodstep start with the root node the two available options are--solution and solution select solution step at solution there are again two options--solution and solution select solution step since solution is not good (valid and possiblecandidatebacktrack to solution and now select solution step since solution is not good (valid and possiblecandidatebacktrack to solution now there are no more options available at solution aso select solution step at solution there are two options--solution and solution select solution step since solution is not good (valid and possiblecandidatebacktrack to solution and now select solution step solution is good (valid and possiblecandidateso the algorithm stops here advantageby terminating searches and not exploring candidates that cannot lead to valid possible solutionsthe backtracking technique reduces the number of nodes examined the algorithm can be used to solve exponential time problems in reasonable amount of time note backtracking is not an optimization technique it just reduces the search space |
24,736 | josephus problem in real-world applicationsespecially in the operating systemmultiple activities have to be performed the biggest issue is not just performing these activities but also completing them in minimum time the johnson' algorithm is used in such applications where an optimal order of execution of different activities has to be determined consider problem that consists of independent tasks otn and two independent processes and if it is specified that must be completed before then johnson' problem can be given asstep determine and times for each task step make two queuesq and where is formed at the beginning of the schedule and is formed at its end step for each taskanalyse and times to determine the smallest time if is the smallest timethen insert the corresponding task at the end of otherwiseinsert the corresponding task at the beginning of in case of tietake as the smallest time note if there is tie between multiple or multiple timesselect the first task in the list consider the table given belowwhich specifies the tasks and time it takes to complete processes and task time to perform time to perform nowfor each taskanalyse and times to determine the smallest time tasks with time less than are assigned to the head of other tasks are assigned to the tail of task time to perform time to perform mintime location tail tail |
24,737 | head tail tail tail mintime location sort the table using the mintime field task time to perform time to perform head tail tail tail tail tail there is an alternative implementation strategy which states that if location has the value tail then the task is added at the front of once all the tasks are assignedhead and tail can be concatenated to create the final complete queue when calculating the efficiency of the johnson' algorithmwe see that the data is processed as one observation at timethereby taking (ntime where is the volume of the data then the data must be sorted which will again take at least ( log ntime sinceo( log nterm dominates johnson' algorithm gives an optimal schedule in ( log ntime |
24,738 | file handling in write program to store records of an employee in employee file the data must be stored using binary file #include #include int main(typedef struct employee int emp_codechar name[ ]}file *fpstruct employee [ ]int ifp fopen("employee txt""wb")if(fp==nullprintf("\ error opening file")exit( )printf("\ enter the details employees")for( ++printf("\ \ enter the employee code:")scanf(,,% "& [iemp_code)printf("\ \ enter the name of the employee")scanf("% " [iname)fwrite(& [ ]sizeof( [ ]) fp)fclose(fp)getch()return output enter the details of employees enter the employee code enter the name of the employeegargi enter the employee code enter the name of the employeenikita write program to read the records stored in 'employee txtfile in binary mode #include #include |
24,739 | int main(typedef struct employee int emp_codechar name[ ]}file *fpstruct employee eint iclrscr()fp fopen("employee txt""rb")if(fp==nullprintf("\ error opening file")exit( )printf("\ the details of the employees are ")while( fread(&esizeof( ) fp)if(feof(fp)breakprintf("\ \ employee code% " emp_code)printf("\ \ name% " name)fclose(fp)getch()return output employee code namegargi employee code namenikita |
24,740 | address calculation sort write program to sort elements of an array using address calculation sort #include #include #define max struct node int datastruct node *next}*nodes[ ]={null}struct node *insert(struct node *startint numstruct node *ptr,*new_nodeptr=startnew_node (struct node*)malloc(sizeof(struct node))new_node->data=numnew_node->next=nullif(start==nullstart new_nodeelse //insert the new node at its right position while((ptr->next->datanext!=null)ptr=ptr->nextif(new_node->data datanew_node->next=ptrstart=new_nodeelse new_node->next=ptr->nextptr->next=new_nodereturn startvoid addr_calc_sort(int arr[],int nint , = ,posfor( = ; < ; ++pos arr[ |
24,741 | nodes[pos]=insert(nodes[pos],arr[ ])for( = ; < ; ++while(nodes[ ]!=nullarr[ ++]=nodes[ ]->datanodes[ ]=nodes[ ]->nextprintf("\nsorted output is")for( = ; < ; ++printf("% \ ",arr[ ])getch()void main(int arr[max], ,nprintf("\ enter the number of elements ")scanf("% ",& )printf("\ enter the elements ")for( = ; < ; ++scanf("% ",&arr[ ])addr_calc_sort(arr, )output enter the number of elements enter the elements sorted output is |
24,742 | answers multiple-choice questions ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( false false true true false false false true true false true false true false true true true true or false false false false true true true false true fill in the blanks dennis ritchie operating system typecasting closing bracket sizeof arguments/parameters byte main( modulus operator (% default case \ %hd calling function function header and function body null ascii codes unary printf( const % calling function call by reference rvalue multiple-choice questions ( ( ( ( ( ( ( ( ( ( ( ( ( false false false false false true true false false false true or false false false false true false |
24,743 | fill in the blanks data structures functions arrays data type root null considered apart from the detailed specifications or implementation input size amortized case index or subscript top peep or peek an attempt is made to insert an element in an arraystack or queue that is already full queue rearfront linear data structure program time complexity average case running time ( modules top down worst omega non-asymptotically is in multiple-choice questions ( ( ( ( ( ( true true false true false false true false true or false true true true true false true false fill in the blanks base address array of arrays index or subscript consecutive pointer data typenameand size the number of elements stored in it integral value fourth multiple-choice questions ( ( ( ( ( ( ( ( ( ( true false true true false false false true true false true or false false false false false true fill in the blanks null-terminated character array zero scanf( convert character into upper case when in dictionary order will come after strrev( morning index operation str is less than str puts null character consecutive - strlen |
24,744 | data structures using multiple-choice questions ( ( ( ( ( ( ( true true true true true true false true true false true or false false false false false fill in the blanks user defined structure declaration structure name typedef zero null character dot operator nested structure self-referential we declare variable of structure union refer to the individual members of structure or union union multiple-choice questions ( ( ( ( ( ( ( false true false false false true avail ( ( two one two one two one node start node there is no memory that can be allocated for the new node to be inserted two true or false true false true true fill in the blanks first multiple-choice questions ( ( ( ( true true true false true or false false true true false false false true false fill in the blanks stack stack we try to delete node from stack that is empty non-tail directly ( left to right |
24,745 | multiple-choice questions ( ( ( ( ( false true false true or false false true false true true fill in the blanks rear input restricted dequeue priority queues dequeue ( circular array or circular doubly linked list queues multiple-choice questions ( ( ( ( ( ( true false true false true or false true false true true fill in the blanks ascendant nodes two siblings structure and contents each node in the tree has either no child or exactly two children and log ( + preorder the estimated probability of occurrence for each possible value of the source character multiple-choice questions ( ( ( ( ( false false true true true or false true false false false false true fill in the blanks two way threaded binary tree right sub tree in-order successor subtracting the height of its right sub-tree from the height of the left sub-tree the left sub-tree of the tree is one level lower than that of the right sub-tree (log ll black and black (the parent of nis the root of the splay tree splay |
24,746 | data structures using multiple-choice questions ( ( ( ( ( false false false true or false true false true false true true fill in the blanks and - tree and - (log / multiple-choice questions ( ( ( ( ( ( ( true false true false false false true true or false true false false true fill in the blanks priority queues partially ordered trees min heap root set of binomial trees that satisfy binomial-heap properties ( collection of heap-ordered trees whether node has lost child since the last time was made the child of another node multiple-choice questions ( ( ( ( ( ( ( true true false true false true true or false false true false true fill in the blanks an isolated node cycle transitive closure bridge terminate multi-graph articulation point bit matrix or boolean matrix tree vertices bi-connected |
24,747 | multiple-choice questions ( ( ( ( ( ( ( ( ( ( ( false true false true true false true true or false false false false true fill in the blanks sorted array ( the process of arranging values in predetermined order merge sort heap sortquick sort bubble sort ( ( log ( pivot element external sorting merge sortquick sort ( log multiple-choice questions ( ( ( ( ( ( false false false true true or false false true false true false fill in the blanks hash function collision hashing probes sentinel value and data value quadratic probing multiple-choice questions ( ( ( ( true true true or false false true true true false true fill in the blanks file file position primary type and size file structure inverted record record number and address database |
24,748 | index terms links - tree abstract data type adjacency matrix algorithms efficiency control structures time and space complexity amortized running time ancestor node arguments arithmetic operators array assigning values calculating the length declaration initializing inputting values multi-dimensional operations of structures pointers strings this page has been reformatted by knovel to provide easier navigation |
24,749 | links array (cont structures two-dimensional union average-case running time avl tree balanced tree operations basic data types best-case running time bi-connected components big- notation binary file binary heap applications deleting inserting binary search binary search tree operations binary tree huffman' tree in-order level-order post-order pre-order traversing binomial heap linked representation operations this page has been reformatted by knovel to provide easier navigation |
24,750 | links bit matrix bitwise operators bottom-up approach breadth-first search break statement tree applications deleting inserting searching btree deleting inserting call by reference circular doubly linked list deleting node inserting new node circular linked list circular queue collision bucket hashing chaining double hashing linear probing open addressing quadratic probing rehashing resolution resolution by chaining comma operator this page has been reformatted by knovel to provide easier navigation |
24,751 | links comparison of sorting algorithms complete binary tree conditional operator continue statement copies critical node data field data management data structure linear and non-linear structures primitive and non-primitive data type decision control statements if statement if-else-if statement if-else statement if statement switch-case statement default degree degree of node deleting dependent quadratic loop depth depth-first search deques dijkstras algorithm directed graph transitive closure directory this page has been reformatted by knovel to provide easier navigation |
24,752 | links doubly linked list deleting node inserting new node edges equality operators expression trees extended binary trees external nodes external sorting fibonacci heap operations structure fifo file attributes operations organization indexed sequential relative file organization sequential organization function call called function calling function functions call by value declaration definition function call this page has been reformatted by knovel to provide easier navigation |
24,753 | links functions (cont passing arrays passing parameters self-referential structures structures general trees generic pointers graph adjacency list adjacency matrix adjacency multi-list applications breadth-first search complete connected depth-first search directed in-degree out-degree regular representation simple directed terminology traversal algorithms weighted hash function division method this page has been reformatted by knovel to provide easier navigation |
24,754 | links hash function (cont mid-square method multiplication method properties hashing applications hash table header linked list height/depth huffman' tree identifiers if-else-if statement if-else statement if statement in-degree index indexing -tree index cylinder surface dense and sparse dense index hashed indices inverted files inverted indices multi-level indices ordered indices primary index secondary index sparse index index table input/output statement this page has been reformatted by knovel to provide easier navigation |
24,755 | links inserting internal nodes iterative statements do-while loop for loop while loop keywords kruskal' algorithm leaf node left successor linear logarithmic loop linear loops linear search linked list applications circular circular doubly de-allocation deleting node doubly header memory allocation multi-linked lists searching linked list versus arrays this page has been reformatted by knovel to provide easier navigation |
24,756 | links linked stack operations pop operation push operation little omega notation ( little notation ll rotation logarithmic loops logical operators loop linear logarithmic nested lr and rl rotations lr rotation merging minimum spanning forest modularization modules multi-graph multiple stacks -way search trees neighbours nested structures null pointer omega notation ( this page has been reformatted by knovel to provide easier navigation |
24,757 | links operation arrays binary search deletion insertion replacement linear search merging searching traversal operations on stack peep pop push operators assignment bitwise equality comma conditional logical precedence chart relational sizeof unary out-degree path peep operation pointer to pointers this page has been reformatted by knovel to provide easier navigation |
24,758 | links pointers arrays generic pointers null pointers pointer arithmetic strings polynomial representation pop operation primary key printf( priority queue array representation deletion implementation insertion linked representation programming language push operation quadratic loop queue applications array representation circular queues delete deques insert linked representation multiple queues operations priority queues this page has been reformatted by knovel to provide easier navigation |
24,759 | programming using turbo +earlier best-selling titles include assembly language primer for the ibm pc and xt and (back at the beginning of the computer revolutionsoul of cp/ acknowledgments my gratitude for the following people (and many otherscannot be fully expressed in this short acknowledgment as alwaysmitch waite had the java thing figured out before anyone else he also let me bounce the applets off him until they did the job and extracted the overall form of the project from miasma of speculation my editorkurt stephanfound great reviewersmade sure everyone was on the same pagekept the ball rollingand gently but firmly ensured that did what was supposed to do harry henderson provided skilled appraisal of the first draftalong with many valuable suggestions richard wrightjr as technical editorcorrected numerous problems with his keen eye for detail jaime ninoph of the university of new orleansattempted to save me from myself and occasionally succeededbut should bear no responsibility for my approach or coding details susan walton has been staunch and much-appreciated supporter in helping to convey the essence of the project to the nontechnical carmela carvajal was invaluable in extending our contacts with the academic world dan scherf not only put the cd-rom togetherbut was tireless in keeping me up-to-date on rapidly evolving software changes finallycecile kaufman ably shepherded the book through its transition from the editing to the production process acclaim for robert lafore' "robert has truly broken new ground with this book nowhere else have seen these topics covered in such clear and easy-to-understandyet completemanner this book is sure to be an indispensable resource and reference to any programmer seeking to advance his or her skills and value beyond the mundane world of data entry screens and windows dialog boxes am especially impressed with the workshop applets some percent of your brain is designed for processing visual data by interactively 'showinghow these algorithms workhe has really managed to find way that almost anyone can use to approach this subject he has raised the bar on this type of book forever --richard wrightjr authoropengl superbible "robert lafore' explanations are always clearaccessibleand practical his java program examples reinforce learning with visual demonstration of each concept you will be able to understand and use every technique right away --harry henderson authorthe internet and the information superhighway and internet how-to " found the tone of the presentation inviting and the use of applets for this topic major plus --jaime ninophd associate professorcomputer science departmentuniversity of new orleans - |
24,760 | this introduction tells you briefly what this book is about why it' different who might want to read it what you need to know before you read it the software and equipment you need to use it how this book is organized what this book is about this book is about data structures and algorithms as used in computer programming data structures are ways in which data is arranged in your computer' memory (or stored on diskalgorithms are the procedures software program uses to manipulate the data in these structures almost every computer programeven simple oneuses data structures and algorithms for exampleconsider program that prints address labels the program might use an array containing the addresses to be printedand simple for loop to step through the arrayprinting each address the array in this example is data structureand the for loopused for sequential access to the arrayexecutes simple algorithm for uncomplicated programs with small amounts of datasuch simple approach might be all you need howeverfor programs that handle even moderately large amounts of dataor that solve problems that are slightly out of the ordinarymore sophisticated techniques are necessary simply knowing the syntax of computer language such as java or +isn' enough this book is about what you need to know after you've learned programming language the material we cover here is typically taught in colleges and universities as second-year course in computer scienceafter student has mastered the fundamentals of programming what' different about this book there are dozens of books on data structures and algorithms what' different about this onethree thingsour primary goal in writing this book is to make the topics we cover easy to understand demonstration programs called workshop applets bring to life the topics we covershowing you step by stepwith "moving pictures,how data structures and algorithms work the example code is written in javawhich is easier to understand than cc++or pascalthe languages traditionally used to demonstrate computer science topics let' look at these features in more detail - |
24,761 | typical computer science textbooks are full of theorymathematical formulasand abstruse examples of computer code this bookon the other handconcentrates on simple explanations of techniques that can be applied to real-world problems we avoid complex proofs and heavy math there are lots of figures to augment the text many books on data structures and algorithms include considerable material on sofware engineering software engineering is body of study concerned with designing and implementing large and complex software projects howeverit' our belief that data structures and algorithms are complicated enough without involving this additional disciplineso we have deliberately de-emphasized software engineering in this book (we'll discuss the relationship of data structures and algorithms to software engineering in ,overview "of course we do use an object-oriented approachand we discuss various aspects of object-oriented design as we go alongincluding mini-tutorial on oop in our primary emphasishoweveris on the data structures and algorithms themselves workshop applets the cd-rom that accompanies this book includes demonstration programsin the form of java appletsthat cover the topics we discuss these appletswhich we call workshop appletswill run on many computer systemsappletviewersand web browsers (see the readme file on the cd-rom for more details on compatibility the workshop applets create graphic images that show you in "slow motionhow an algorithm works for examplein one workshop appleteach time you push buttona bar chart shows you one step in the process of sorting the bars into ascending order the values of variables used in the sorting algorithm are also shownso you can see exactly how the computer code works when executing the algorithm text displayed in the picture explains what' happening another applet models binary tree arrows move up and down the treeso you can follow the steps involved in inserting or deleting node from the tree there are more than workshop applets--at least one for every major topic in the book these workshop applets make it far more obvious what data structure really looks likeor what an algorithm is supposed to dothan text description ever could of coursewe provide text description as well the combination of workshop appletsclear textand illustrations should make things easy these workshop applets are standalone graphics-based programs you can use them as learning tool that augments the material in the book (note that they're not the same as the example code found in the text of the bookwhich we'll discuss next java example code the java language is easier to understand (and writethan languages such as and +the biggest reason for this is that java doesn' use pointers although it surprises some peoplepointers aren' necessary for the creation of complex data structures and algorithms in facteliminating pointers makes such code not only easier to write and to understandbut more secure and less prone to errors as well java is modern object-oriented languagewhich means we can use an object-oriented approach for the programming examples this is importantbecause object-oriented programming (oopoffers compelling advantages over the old-fashioned procedural - |
24,762 | if you aren' familiar with oop it' not that hard to understandespecially in pointer-free environment such as java we'll explain the basics of oop in who this book is for this book can be used as text in data structures and algorithms coursetypically taught in the second year of computer science curriculum howeverit is also designed for professional programmers and for anyone else who needs to take the next step up from merely knowing programming language because it' easy to understandit is also appropriate as supplemental text to more formal course who this book is for this book can be used as text in data structures and algorithms coursetypically taught in the second year of computer science curriculum howeverit is also designed for professional programmers and for anyone else who needs to take the next step up from merely knowing programming language because it' easy to understandit is also appropriate as supplemental text to more formal course the software you need to use this book all the software you need to use this book is included on the accompanying cd-rom to run the workshop applets you need web browser or an appletviewer utility such as the one in the sun microsystems java development kit (jdkboth browser and the jdk are included on the cd-rom to compile and run the example programs you'll need the jdk microsoft windows and various other platforms are supported see the readme file on the included cd-rom for details on supported platforms and equipment requirements how this book is organized this section is intended for teachers and others who want quick overview of the contents of the book it assumes you're already familiar with the topics and terms involved in study of data structures and algorithms (if you can' wait to get started with the workshop appletsread appendix "how to run the workshop applets and example programs,and the readme file on the cd-rom first the first two are intended to ease the reader into data structures and algorithms as painlessly as possible "overview,presents an overview of the topics to be discussed and introduces small number of terms that will be needed later on for readers unfamiliar with objectoriented programmingit summarizes those aspects of this discipline that will be needed in the balance of the bookand for programmers who know +but not javathe key differences between these languages are reviewed "arrays,focuses on arrays howeverthere are two subtopicsthe use of classes to encapsulate data storage structures and the class interface searchinginsertionand deletion in arrays and ordered arrays are covered linear searching and binary searching are explained workshop applets demonstrate these algorithms with unordered and ordered arrays in "simple sorting,we introduce three simple (but slowsorting techniquesthe bubble sortselection sortand insertion sort each is demonstrated by workshop applet - |
24,763 | abstract data types (adts)the stackqueueand priority queue these structures reappear later in the bookembedded in various algorithms each is demonstrated by workshop applet the concept of adts is discussed "linked lists,introduces linked listsincluding doubly linked lists and doubleended lists the use of references as "painless pointersin java is explained workshop applet shows how insertionsearchingand deletion are carried out in "recursion,we explore recursionone of the few topics that is not data structure many examples of recursion are givenincluding the towers of hanoi puzzle and the mergesortwhich are demonstrated by workshop applets "advanced sorting,delves into some advanced sorting techniquesshellsort and quicksort workshop applets demonstrate shellsortpartitioning (the basis of quicksort)and two flavors of quicksort in "binary trees,we begin our exploration of trees this covers the simplest popular tree structureunbalanced binary search trees workshop applet demonstrates insertiondeletionand traversal of such trees "red-black trees,explains red-black treesone of the most efficient balanced trees the workshop applet demonstrates the rotations and color switches necessary to balance the tree in trees and external storage,we cover trees as an example of multiway trees workshop applet shows how they work we also discuss the relationship of trees to -treeswhich are useful in storing external (diskfiles "hash tables,moves into new fieldhash tables workshop applets demonstrate several approacheslinear and quadratic probingdouble hashingand separate chaining the hash-table approach to organizing external files is discussed in "heaps,we discuss the heapa specialized tree used as an efficient implementation of priority queue "graphs,and "weighted graphs,deal with graphsthe first with unweighted graphs and simple searching algorithmsand the second with weighted graphs and more complex algorithms involving the minimum spanning trees and shortest paths in "when to use what,we summarize the various data structures described in earlier with special attention to which structure is appropriate in given situation appendix "how to run the workshop applets and example programs,tells how to use the java development kit (the jdkfrom sun microsystemswhich can be used to run the workshop applets and the example programs the readme file on the included cd-rom has additional information on these topics appendix "further reading,describes some books appropriate for further reading on data structures and other related topics enjoy yourselfwe hope we've made the learning process as painless as possible ideallyit should even be fun let us know if you think we've succeeded in reaching this idealor if notwhere you think improvements might be made |
24,764 | list overview arrays simple sorting overview overview as you start this bookyou may have some questionswhat are data structures and algorithmswhat good will it do me to know about themwhy can' just use arrays and for loops to handle my datawhen does it make sense to apply what learn herethis attempts to answer these questions we'll also introduce some terms you'll need to knowand generally set the stage for the more detailed to follow nextfor those of you who haven' yet been exposed to an object-oriented languagewe'll briefly explain enough about oop to get you started finallyfor +programmers who don' know javawe'll point out some of the differences between these languages overview overview as you start this bookyou may have some questionswhat are data structures and algorithmswhat good will it do me to know about themwhy can' just use arrays and for loops to handle my datawhen does it make sense to apply what learn herethis attempts to answer these questions we'll also introduce some terms you'll need to knowand generally set the stage for the more detailed to follow |
24,765 | briefly explain enough about oop to get you started finallyfor +programmers who don' know javawe'll point out some of the differences between these languages overview of data structures another way to look at data structures is to focus on their strengths and weaknesses in this section we'll provide an overviewin the form of tableof the major data storage structures we'll be discussing in this book this is bird' -eye view of landscape that we'll be covering later at ground levelso don' be alarmed if it looks bit mysterious table shows the advantages and disadvantages of the various data structures described in this book table characteristics of data structures data structure advantages disadvantages array quick insertionvery fast access if index known slow searchslow deletionfixed size ordered array quicker search than unsorted array slow insertion and deletionfixed size stack provides last-infirst-out access slow access to other items queue provides first-infirst-out access slow access to other items linked list quick insertionquick deletion slow search binary tree quick searchinsertiondeletion (if tree remains balanceddeletion algorithm is complex red-black tree quick searchinsertiondeletion tree always balanced complex tree quick searchinsertiondeletion tree always balanced similar trees good for disk storage complex hash table very fast access if key known fast insertion slow deletionaccess slow if key not knowninefficient memory usage heap fast insertiondeletionslow access to other items access to largest item graph models real-world situations some algorithms are slow and complex |
24,766 | data typesor adts we'll describe what this means in "linked lists "overview of algorithms many of the algorithms we'll discuss apply directly to specific data structures for most data structuresyou need to know how to insert new data item search for specified item delete specified item you may also need to know how to iterate through all the items in data structurevisiting each one in turn so as to display it or perform some other action on it one important algorithm category is sorting there are many ways to sort dataand we devote "simple sorting,and "advanced sorting,to these algorithms the concept of recursion is important in designing certain algorithms recursion involves method ( functioncalling itself we'll look at recursion in "recursion definitions let' look at few of the terms that we'll be using throughout this book database we'll use the term database to refer to all the data that will be dealt with in particular situation we'll assume that each item in database has similar format as an exampleif you create an address book using the cardfile programall the cards you've created constitute database the term file is sometimes used in this sensebut because our database is often stored in the computer' memory rather than on diskthis term can be misleading the term database can also refer to large program consisting of many data structures and algorithmswhich relate to each other in complex ways howeverwe'll restrict our use of the term to the more modest definition record records are the units into which database is divided they provide format for storing information in the cardfile programeach card represents record record includes all the information about some entityin situation in which there are many such entities record might correspond to person in personnel filea car part in an auto supply inventoryor recipe in cookbook file field record is usually divided into several fields field holds particular kind of data in the cardfile program there are really only two fieldsthe index line (above the double line |
24,767 | particular kind of data figure shows the index line field as holding person' name more sophisticated database programs use records with more fields than cardfile has figure shows such recordwhere each line represents distinct field in java programrecords are usually represented by objects of an appropriate class (in crecords would probably be represented by structures individual variables within an object represent data fields fields within class object are called fields in java (but members in and ++key to search for record within database you need to designate one of the record' fields as key you'll search for the record with specific key for examplein the cardfile program you might search in the index-line field for the key "brown when you find the record with this keyyou'll be able to access all its fieldsnot just the key we might say that the key unlocks the entire record in cardfile you can also search for individual words or phrases in the rest of the data on the cardbut this is actually all one field the program searches through the text in the entire field even if all you're looking for is the phone number this kind of text search isn' very efficientbut it' flexible because the user doesn' need to decide how to divide the card into fields figure record with multiple fields in more full-featured database programyou can usually designate any field as the key in figure for exampleyou could search by zip code and the program would find all employees who live in that zip code search key the key value you're looking for in search is called the search key the search key is compared with the key field of each record in turn if there' matchthe record can be returned or displayed if there' no matchthe user can be informed of this fact object-oriented programming this section is for those of you who haven' been exposed to object-oriented programming howevercaveat emptor we cannotin few pagesdo justice to all the innovative new ideas associated with oop our goal is merely to make it possible for you |
24,768 | into an object-oriented java programmerbut it should make it possible for you to follow the example programs if after reading this section and examining some of the sample code in the following you still find the whole oop business as alien as quantum physicsthen you may need more thorough exposure to oop see the reading list in appendix "further reading,for suggestions problems with procedural languages oop was invented because procedural languagessuch as cpascaland basicwere found to be inadequate for large and complex programs why was thisthe problems have to do with the overall organization of the program procedural programs are organized by dividing the code into functions (called procedures or subroutines in some languagesgroups of functions could form larger units called modules or files crude organizational units one difficulty with this kind of function-based organization was that it focused on functions at the expense of data there weren' many options when it came to data to simplify slightlydata could be local to particular function or it could be global-accessible to all functions there was no way (at least not flexible wayto specify that some functions could access variable and others couldn' this caused problems when several functions needed to access the same data to be available to more than one functionsuch variables had to be globalbut global data could be accessed inadvertently by any function in the program this lead to frequent programming errors what was needed was way to fine-tune data accessibilityallowing variables to be available to functions with need to access itbut hiding it from others poor modeling of the real world it is also hard to conceptualize real-world problem using procedural languages functions carry out taskwhile data stores informationbut most real-world objects do both these things the thermostat on your furnacefor examplecarries out tasks (turning the furnace on and offbut also stores information (the actual current temperature and the desired temperatureif you wrote thermostat control programyou might end up with two functionsfurnace_on(and furnace_off()but also two global variablescurrenttemp (supplied by thermometerand desiredtemp (set by the userhoweverthese functions and variables wouldn' form any sort of programming unitthere would be no unit in the program you could call thermostat the only such unit would be in the programmer' mind for large programswhich might contain hundreds of entities like thermostatsthis procedural approach made things chaoticerror-proneand sometimes impossible to implement at all objects in nutshell the idea of objects arose in the programming community as solution to the problems with procedural languages objects |
24,769 | functions and variables thermostat objectfor examplewould contain not only furnace_on(and furnace_off(functionsbut also currenttemp and desiredtemp incidentallybefore going further we should note that in javafunctions are called methods and variables are called fields this new entitythe objectsolves several problems simultaneously not only does programming object correspond more accurately to objects in the real worldit also solves the problem engendered by global data in the procedural model the furnace_on(and furnace_off(methods can access currenttemp and desiredtemp these variables are hidden from methods that are not part of thermostathoweverso they are less likely to be accidentally changed by rogue method classes you might think that the idea of an object would be enough for one programming revolutionbut there' more early onit was realized that you might want to make several objects of the same type maybe you're writing furnace control program for an entire apartment housefor exampleand you need several dozen thermostat objects in your program it seems shame to go to the trouble of specifying each one separately thusthe idea of classes was born class is specification-- blueprint--for one or more objects here' how thermostat classfor examplemight look in javaclass thermostat private float currenttemp()private float desiredtemp()public void furnace_on(/method body goes here public void furnace_off(/method body goes here /end class thermostat the java keyword class introduces the class specificationfollowed by the name you want to give the classhere it' thermostat enclosed in curly brackets are the fields and methods (variables and functionsthat make up the class we've left out the body of the methodsnormally there would be many lines of program code for each one programmers will recognize this syntax as similar to structurewhile +programmers will notice that it' very much like class in ++except that there' no semicolon at the end (why did we need the semicolon in +anyway?creating objects specifying class doesn' create any objects of that class (in the same way specifying structure in doesn' create any variables to actually create objects in java you must use the keyword new at the same time an object is createdyou need to store |
24,770 | what' referencewe'll discuss references in more detail later in the meantimethink of it as name for an object (it' actually the object' addressbut you don' need to know that here' how we would create two references to type thermostatcreate two new thermostat objectsand store references to them in these variablesthermostat therm therm /create two references therm new thermostat()/create two objects and therm new thermostat()/store references to them incidentallycreating an object is also called instantiating itand an object is often referred to as an instance of class accessing object methods once you've specified class and created some objects of that classother parts of your program need to interact with these objects how do they do thattypicallyother parts of the program interact with an object' methods (functions)not with its data (fieldsfor exampleto tell the therm object to turn on the furnacewe would say therm furnace_on()the dot operator associates an object with one of its methods (or occasionally with one of its fieldsat this point we've covered (rather telegraphicallyseveral of the most important features of oop to summarizeobjects contain both methods (functionsand fields (dataa class is specification for any number of objects to create an objectyou use the keyword new in conjunction with the class name to invoke method for particular object you use the dot operator these concepts are deep and far-reaching it' almost impossible to assimilate them the first time you see themso don' worry if you feel bit confused as you see more classes and what they dothe mist should start to clear runnable object-oriented program let' look at an object-oriented program that runs and generates actual output it features class called bankaccount that models checking account at bank the program creates an account with an opening balancedisplays the balancemakes deposit and withdrawaland then displays the new balance here' the listing for bank java/bank java |
24,771 | /to run this programc>java bankapp import java io */for / ///////////////////////////////////////////////////////////////class bankaccount private double balance/account balance public bankaccount(double openingbalance/constructor balance openingbalancepublic void deposit(double amountbalance balance amountpublic void withdraw(double amountwithdrawal balance balance amount/makes deposit /makes public void display(/displays balance system out println("balance=balance)/end class bankaccount ///////////////////////////////////////////////////////////////class bankapp public static void main(string[argsbankaccount ba new bankaccount( )/create acct system out print("before transactions")ba display()/display balance ba deposit( )ba withdraw( )/make deposit /make withdrawal system out print("after transactions")ba display()/display balance /end main(/end class bankapp |
24,772 | before transactionsbalance= after transactionsbalance= there are two classes in bank java the first onebankaccountcontains the fields and methods for our bank account we'll examine it in detail in moment the second classbankappplays special role the bankapp class to execute the program from dos boxyou type java bankapp following the cpromptc:java bankapp this tells the java interpreter to look in the bankapp class for the method called main(every java application must have main(methodexecution of the program starts at the beginning of main()as you can see in the bank java listing (you don' need to worry yet about the string[args argument in main(the main(method creates an object of class bankaccountinitialized to value of which is the opening balancewith this statementbankaccount ba new bankaccount( )/create acct the system out print(method displays the string used as its argumentbefore transactions,and the account displays its balance with the following statementba display()the program then makes deposit toand withdrawal fromthe accountba deposit( )ba withdraw( )finallythe program displays the new account balance and terminates the bankaccount class the only data field in the bankaccount class is the amount of money in the accountcalled balance there are three methods the deposit(method adds an amount to the balancewithdrawal(subtracts an amountand display(displays the balance constructors the bankaccount class also features constructor constructor is special method that' called automatically whenever new object is created constructor always has exactly the same name as the classso this one is called bankaccount(this constructor has one argumentwhich is used to set the opening balance when the account is created |
24,773 | constructor in this programyou would have needed an additional call to deposit(to put the opening balance in the account public and private notice the keywords public and private in the bankaccount class these keywords are access modifiers and determine what methods can access method or field the balance field is preceded by private field or method that is private can only be accessed by methods that are part of the same class thusbalance cannot be accessed by statements in main()because main(is not method in bankaccount howeverall the methods in bankaccount have the access modifier publicso they can be accessed by methods in other classes that' why statements in main(can call deposit()withdrawal()and display(data fields in class are typically made private and methods are made public this protects the datait can' be accidentally modified by methods of other classes any outside entity that needs to access data in class must do so using method of the same class data is like queen beekept hidden in the middle of the hivefed and cared for by worker-bee methods inheritance and polymorphism we'll briefly mention two other key features of object-oriented programminginheritance and polymorphism inheritance is the creation of one classcalled the extended or derived classfrom another class called the base class the extended class has all the features of the base classplus some additional features for examplea secretary class might be derived from more general employee classand include field called typingspeed that the employee class lacked in javainheritance is also called subclassing the base class may be called the superclassand the extended class may be called the subclass inheritance makes it easy to add features to an existing class and is an important aid in the design of programs with many related classes inheritance thus makes it easy to reuse classes for slightly different purposea key benefit of oop polymorphism involves treating objects of different classes in the same way for polymorphism to workthese different classes must be derived from the same base class in practicepolymorphism usually involves method call that actually executes different methods for objects of different classes for examplea call to display(for secretary object would invoke display method in the secretary classwhile the exact same call for manager object would invoke different display method in the manager class polymorphism simplifies and clarifies program design and coding for those not familiar with theminheritance and polymorphism involve significant additional complexity to keep the focus on data structures and algorithmswe have avoided these features in our example programs inheritance and polymorphism are important and powerful aspects of oop but are not necessary for the explanation of data structures and algorithms software engineering |
24,774 | algorithms with on software engineering we don' follow that approachbut let' briefly examine software engineering and see how it fits into the topics we discuss in this book software engineering is the study of how to create large and complex computer programsinvolving many programmers it focuses on the overall design of the program and on the creation of that design from the needs of the end users software engineering is concerned with life cycle of software projectwhich includes specificationdesignverificationcodingtestingproductionand maintenance it' not clear that mixing software engineering on one handand data structures and algorithms on the otheractually helps the student understand either topic software engineering is rather abstract and is difficult to grasp until you've been involved yourself in large project data structures and algorithmson the other handis nuts-and-bolts discipline concerned with the details of coding and data storage accordingly we focus on the nuts-and-bolts aspects of data structures and algorithms how do they really workwhat structure or algorithm is best in particular situationwhat do they look like translated into java codeas we notedour intent is to make the material as easy to understand as possible for further readingwe mention some books on software engineering in appendix java for +programmers if you're +programmer who has not yet encountered javayou might want to read this section we'll mention several ways in which java differs from +this section is not intended to be primer on java we don' even cover all the differences between +and java we're only interested in few java features that might make it hard for +programmers to figure out what' going on in the example programs no pointers the biggest difference between +and java is that java doesn' use pointers to +programmer this may at first seem quite amazing how can you get along without pointersthroughout this book we'll be using pointer-free code to build complex data structures you'll see that it' not only possiblebut actually easier than using +pointers actually java only does away with explicit pointers pointersin the form of memory addressesare still thereunder the surface it' sometimes said that in javaeverything is pointer this is not completely truebut it' close let' look at the details references java treats primitive data types (such as intfloatand doubledifferently than objects look at these two statementsint intvarbankaccount bc /an int variable called intvar /reference to bankaccount object in the first statementa memory location called intvar actually holds numerical value such as (assuming such value has been placed therehoweverthe memory location bc does not hold the data of bankaccount object insteadit contains the address of bankaccount object that is actually stored elsewhere in memory the |
24,775 | actuallybc won' hold reference if it has not been assigned an object at some prior point in the program before being assigned an objectit holds reference to special object called null in the same wayintvar won' hold numerical value if it' never been assigned one the compiler will complain if you try to use variable that has never been assigned value in ++the statement bankaccount bc actually creates an objectit sets aside enough memory to hold all the object' data in javaall this statement creates is place to put an object' memory address you can think of reference as pointer with the syntax of an ordinary variable ( +has reference variablesbut they must be explicitly specified with the symbol assignment it follows that the assignment operator (=operates differently with java objects than with +objects in ++the statement bc bc copies all the data from an object called bc into different object called bc following this statement are two objects with the same data in javaon the other handthis same assignment statement copies the memory address that bc refers to into bc both bc and bc now refer to exactly the same objectthey are references to it this can get you into trouble if you're not clear on what the assignment operator does following the assignment statement shown abovethe statement bc withdraw( )and the statement bc withdraw( )both withdraw $ from the same bank account object suppose you actually want to copy data from one object to another in this case you must make sure you have two separate objects to begin withand then copy each field separately the equal sign won' do the job the new operator any object in java must be created using new howeverin javanew returns referencenot pointer as in +thuspointers aren' necessary to use new here' one way to create an objectbankaccount ba ba new bankaccount()eliminating pointers makes for more secure system as programmeryou can' find out the actual address of ba so you can' accidentally corrupt it howeveryou probably don' need to know it unless you're planning something wicked |
24,776 | longer needin ++you use delete in javayou don' need to worry about it java periodically looks through each block of memory that was obtained with new to see if valid references to it still exist if there are no such referencesthe block is returned to the free memory store this is called garbage collection in +almost every programmer at one time or another forgets to delete memory blockscausing "memory leaksthat consume system resourcesleading to bad performance and even crashing the system memory leaks can' happen in java (or at least hardly everarguments in ++pointers are often used to pass objects to functions to avoid the overhead of copying large object in javaobjects are always passed as references this also avoids copying the object void method (bankaccount ba new bankaccount( )method (ba )void method (bankaccount acctin this codethe references ba and acct both refer to the same object primitive data typeson the other handare always passed by value that isa new variable is created in the function and the value of the argument is copied into it equality and identity in javaif you're talking about primitive typesthe equality operator (==will tell you whether two variables have the same valueint intvar int intvar intvar if(intvar =intvar system out println("they're equal")this is the same as the syntax in and ++but in javabecause they use referencesrelational operators work differently with objects the equality operatorwhen applied to objectstells you whether two references are identicalthat iswhether they refer to the same objectcarpart cp new carpart("fender")carpart cp cp if(cp =cp system out println("they're identical")in +this operator would tell you if two objects contained the same data if you want to see whether two objects contain the same data in javayou must use the equals(method of the object class |
24,777 | carpart cp cp ifcp equals(cp system out println("they're equal")this works because all objects in java are implicitly derived from the object class overloaded operators this is easythere are no overloaded operators in java in ++you can redefine +*=and most other operators so they behave differently for objects of particular class no such redefinition is possible in java insteaduse method such as add(primitive variable types the primitive or built-in variable types in java are shown in table table primitive data types name size in bits range of values boolean true or false byte - to + char '\ to '\uffffshort - , to + , int - , , , to + , , , long - , , , , , , to + , , , , , , float approximately - double approximately digits - to + significant digits + to significant unlike and ++which use integers for true/false valuesboolean is distinct type in java type char is unsigned and uses two bytes to accommodate the unicode character representation schemewhich can handle international characters the int type varies in size in and ++depending on the specific computer platformin java an int is always bits |
24,778 | need no suffix literals of type long use suffix (as in )literals of the other integer types need no suffix java is more strongly typed than and ++many conversions that were automatic in those languages require an explicit cast in java all types not shown in table such as stringare classes input/output for the console-mode applications we'll be using for example programs in this booksome clunky-looking but effective constructions are available for input and output they're quite different from the workhorse cout and cin approach in +and printf(and scanf(in all the input/output routines we show here require the line import java io *at the beginning of your source file output you can send any primitive type (numbers and characters)and string objects as wellto the display with these statementssystem out print(var)system out println(var)/displays varno linefeed /displays varthen starts new line the first statement leaves the cursor on the same linethe second statement moves it to the beginning of the next line because output is bufferedyou'll need to use println(method as the last statement in series to actually display everything it causes the contents of the buffer to be transferred to the displaysystem out print(var )system out print(var )system out println(var )displayed /nothing appears /nothing appears /var var and var are all you can also use system out flush(to cause the buffer to be displayed without going to new linesystem out print("enter your name")system out flush()inputting string input is considerably more involved than output in generalyou want to read any input as string object if you're actually inputting something elsesuch as character or numberyou then convert the string object to the desired type |
24,779 | public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return sthis method returns string objectwhich is composed of characters typed on the keyboard and terminated with the enter key besides importing java io *you'll also need to add throws ioexception to all input methodsas shown in the preceding code the details of the inputstreamreader and bufferedreader classes need not concern us here this approach was introduced with version of sun microsystemsjava development kit (jdkearlier versions of the jdk used the system in object to read individual characterswhich were then concatenated to form string object the termination of the input was signaled by newline ('\ 'charactergenerated when the user pressed enter here' the code for this older approachpublic string getstring(throws ioexception string ""int chwhile(ch=system in read()!- &(char)ch !'\ns +(char)chreturn shere characters are read as integerswhich allows the negative value - to signal an end-of-file (eofthe while loop reads characters until an end-of-file or newline occurs you'll need to use this version of getstring(if you're using older versions of the jdk inputting character suppose you want your program' user to enter character (by enter we mean typing something and pressing the enter key the user may enter single character or (incorrectlymore than one thereforethe safest way to read character involves reading string and picking off its first character with the charat(methodpublic static char getchar(throws ioexception string getstring()return charat( )the charat(method of the string class returns character at the specified position in the string objecthere we get the first one the approach shown avoids extraneous |
24,780 | subsequent input inputting integers to read numbersyou make string object as shown before and convert it to the type you want using conversion method here' methodgetint()that converts input into type int and returns itpublic int getint(throws ioexception string getstring()return integer parseint( )the parseint(method of class integer converts the string to type int similar routineparselong()can be used to convert type long for simplicitywe don' show any error-checking in the input routines in the example programs the user must type appropriate input or an exception will occur with the code shown here the exception will cause the program to terminate in serious program you should analyze the input string before attempting to convert itand also catch any exceptions and process them appropriately inputting floating-point numbers types float and double can be handled in somewhat the same way as integersbut the conversion process is more complex here' how you read number of type doublepublic int getdouble(throws ioexception string getstring()double adub double valueof( )return adub doublevalue()the string is first converted to an object of type double (uppercase )which is "wrapperclass for type double method of double called doublevalue(then converts the object to type double for type floatthere' an equivalent float classwhich has equivalent valueof(and floatvalue(methods java library data structures the java java util package contains data structuressuch as vector (an extensible array)stackdictionaryand hashtable in this book we'll largely ignore these built-in classes we're interested in teaching fundamentalsnot in the details of particular data-structure implementation howeversuch class librarieswhether those that come with java or others available from third-party developerscan offer rich source of versatiledebugged storage classes this book should equip you with the knowledge you'll need to know what sort of data structure you need and the fundamentals of how it works then you can decide whether you should write your own classes or use pre-written library classes if you use class libraryyou'll know which classes you need and whether particular implementation works in your |
24,781 | summary data structure is the organization of data in computer' memory or in disk file the correct choice of data structure allows major improvements in program efficiency examples of data structures are arraysstacksand linked lists an algorithm is procedure for carrying out particular task in javaan algorithm is usually implemented by class method many of the data structures and algorithms described in this book are most often used to build databases some data structures are used as programmer' toolsthey help execute an algorithm other data structures model real-world situationssuch as telephone lines running between cities database is unit of data storage comprising many similar records record often represents real-world objectsuch as an employee or car part record is divided into fields each field stores one characteristic of the object described by the record key is field in record that' used to carry out some operation on the data for examplepersonnel records might be sorted by lastname field database can be searched for all records whose key field has certain value this value is called search key summary data structure is the organization of data in computer' memory or in disk file the correct choice of data structure allows major improvements in program efficiency examples of data structures are arraysstacksand linked lists an algorithm is procedure for carrying out particular task in javaan algorithm is usually implemented by class method many of the data structures and algorithms described in this book are most often used to build databases some data structures are used as programmer' toolsthey help execute an algorithm other data structures model real-world situationssuch as telephone lines running between cities |
24,782 | record often represents real-world objectsuch as an employee or car part record is divided into fields each field stores one characteristic of the object described by the record key is field in record that' used to carry out some operation on the data for examplepersonnel records might be sorted by lastname field database can be searched for all records whose key field has certain value this value is called search key the array workshop applet suppose that you're coaching kids-league baseball team and you want to keep track of which players are present at the practice field what you need is an attendancemonitoring program for your laptopa program that maintains database of the players who have shown up for practice you can use simple data structure to hold this data there are several actions you would like to be able to performinsert player into the data structure when the player arrives at the field check to see if particular player is present by searching for his or her number in the structure delete player from the data structure when the player goes home these three operations will be the fundamental ones in most of the data storage structures we'll study in this book in this book we'll often begin the discussion of particular data structure by demonstrating it with workshop applet this will give you feeling for what the structure and its algorithms dobefore we launch into detailed discussion and demonstrate actual example code the workshop applet called array shows how an array can be used to implement insertionsearchingand deletion start up this appletas described in appendix awith :appletviewer array html figure shows what you'll see there' an array with elements of which have data items in them you can think of these items as representing your baseball players imagine that each player has been issued team shirt with the player' number on the back to make things visually interestingthe shirts come in wide variety of colors you can see each player' number and shirt color in the array |
24,783 | this applet demonstrates the three fundamental procedures mentioned abovethe ins button inserts new data item the find button searches for specified data item the del button deletes specified data item using the new buttonyou can create new array of size you specify you can fill this array with as many data items as you want using the fill button fill creates set of items and randomly assigns them numbers and colors the numbers are in the range to you can' create an array of more than cellsand you can'tof coursefill more data items than there are array cells alsowhen you create new arrayyou'll need to decide whether duplicate items will be allowedwe'll return to this question in moment the default value is no duplicates and the no dups radio button is selected to indicate this insertion start with the default arrangement of cells and data items and the no dups button checked you insert baseball player' number into the array when the player arrives at the practice fieldhaving been dropped off by parent to insert new itempress the ins button once you'll be prompted to enter the value of the itementer key of item to insert type numbersay into the text field in the upper-right corner of the applet (yesit is hard to get three digits on the back of kid' shirt press ins again and the applet will confirm your choicewill insert item with key final press of the button will cause data itemconsisting of this value and random colorto appear in the first empty cell in the array the prompt will say something likeinserted item with key at index each button press in workshop applet corresponds to step that an algorithm carries out the more steps requiredthe longer the algorithm takes in the array workshop applet the insertion process is very fastrequiring only single step this is because |
24,784 | where this is because it knows how many items are already in the array the new item is simply inserted in the next available space searching and deletionhoweverare not so fast in no-duplicates mode you're on your honor not to insert an item with the same key as an existing item if you dothe applet displays an error messagebut it won' prevent the insertion the assumption is that you won' make this mistake searching click the find button you'll be prompted for the key number of the person you're looking for pick number that appears on an item somewhere in the middle of the array type in the number and repeatedly press the find button at each button pressone step in the algorithm is carried out you'll see the red arrow start at cell and move methodically down the cellsexamining new one each time you push the button the index number in the message checking next cellindex will change as you go along when you reach the specified itemyou'll see the message have found item with key or whatever key value you typed in assuming duplicates are not allowedthe search will terminate as soon as an item with the specified key value is found if you have selected key number that is not in the arraythe applet will examine every occupied cell in the array before telling you that it can' find that item notice that (again assuming duplicates are not allowedthe search algorithm must look through an average of half the data items to find specified item items close to the beginning of the array will be found soonerand those toward the end will be found later if is the number of itemsthen the average number of steps needed to find an item is / in the worst-case scenariothe specified item is in the last occupied celland steps will be required to find it as we notedthe time an algorithm takes to execute is proportional to the number of stepsso searching takes much longer on the average ( / stepsthan insertion (one stepdeletion to delete an item you must first find it after you type in the number of the item to be deletedrepeated button presses will cause the arrow to movestep by stepdown the array until the item is located the next button press deletes the item and the cell becomes empty (strictly speakingthis step isn' necessary because we're going to copy over this cell anywaybut deleting the item makes it clearer what' happening implicit in the deletion algorithm is the assumption that holes are not allowed in the array hole is one or more empty cells that have filled cells above them (at higher index numbersif holes are allowedall the algorithms become more complicated because they must check to see if cell is empty before examining its contents alsothe algorithms become less efficient because they must waste time looking at unoccupied cells for these reasonsoccupied cells must be arranged contiguouslyno holes allowed thereforeafter locating the specified item and deleting itthe applet must shift the contents of each subsequent cell down one space to fill in the hole figure shows an |
24,785 | figure deleting an item if the item in cell ( in the figureis deletedthen the item in would shift into the item in would shift into and so on to the last occupied cell during the deletion processonce the item is locatedthe applet will shift down the contents of the higherindexed cells as you continue to press the del button deletion requires (assuming no duplicates are allowedsearching through an average of / elementsand then moving the remaining elements (an average of / movesto fill up the resulting hole this is steps in all the duplicates issue when you design data storage structureyou need to decide whether items with duplicate keys will be allowed if you're talking about personnel file and the key is an employee numberthen duplicates don' make much sensethere' no point in assigning the same number to two employees on the other handif the key value is last namesthen there' distinct possibility several employees will have the same key valueso duplicates should be allowed of coursefor the baseball playersduplicate numbers should not be allowed it would be hard to keep track of the players if more than one wore the same number the array workshop applet lets you select either option when you use new to create new arrayyou're prompted to specify both its size and whether duplicates are permitted use the radio buttons dups ok or no dups to make this selection if you're writing data storage program in which duplicates are not allowedyou may need to guard against human error during an insertion by checking all the data items in the array to ensure that none of them already has the same key value as the item being inserted this is inefficienthoweverand increases the number of steps required for an insertion from one to for this reasonour applet does not perform this check searching with duplicates allowing duplicates complicates the search algorithmas we noted even if it finds matchit must continue looking for possible additional matches until the last occupied cell at least this is one approachyou could also stop after the first match it depends on whether the question is "find me everyone with blue eyesor "find me someone with blue eyes when the dups ok button is selectedthe applet takes the first approachfinding all items matching the search key this always requires stepsbecause the algorithm must go all the way to the last occupied cell |
24,786 | insertion is the same with duplicates allowed as when they're nota single step inserts the new item but rememberif duplicates are not allowedand there' possibility the user will attempt to input the same key twiceyou may need to check every existing item before doing an insertion deletion with duplicates deletion may be more complicated when duplicates are alloweddepending on exactly how "deletionis defined if it means to delete only the first item with specified valuethenon the averageonly / comparisons and / moves are necessary this is the same as when no duplicates are allowed but if deletion means to delete every item with specified key valuethen the same operation may require multiple deletions this will require checking cells and (probablymoving more than / cells the average depends on how the duplicates are distributed throughout the array the applet assumes this second meaning and deletes multiple items with the same key this is complicatedbecause each time an item is deletedsubsequent items must be shifted farther for exampleif three items are deletedthen items beyond the last deletion will need to be shifted three spaces to see how this worksset the applet to dups ok and insert three or four items with the same key then try deleting them table shows the average number of comparisons and moves for the three operationsfirst where no duplicates are allowed and then where they are allowed is the number of items in the array inserting new item counts as one move you can explore these possibilities with the array workshop applet table duplicates ok versus no duplicates no duplicates duplicates ok search / comparisons comparisons insertion no comparisonsone move no comparisonsone move deletion / comparisonsn/ moves comparisonsmore than / moves the difference between and / is not usually considered very significantexcept when fine-tuning program of more importanceas we'll discuss toward the end of this is whether an operation takes one stepn stepslog(nstepsor steps not too swift one of the significant things to notice when using the array applet is the slow and methodical nature of the algorithms with the exception of insertionthe algorithms involve stepping through some or all of the cells in the array different data structures offer much |
24,787 | later in this and others throughout this book the basics of arrays in java the preceding section showed graphically the primary algorithms used for arrays now we'll see how to write programs to carry out these algorithmsbut we first want to cover few of the fundamentals of arrays in java if you're java expertyou can skip ahead to the next sectionbut even and +programmers should stick around arrays in java use syntax similar to that in and +(and not that different from other languages)but there are nevertheless some unique aspects to the java approach creating an array as we noted in there are two kinds of data in javaprimitive types (such as int and double)and objects in many programming languages (even object-oriented ones like ++arrays are primitive typebut in java they're treated as objects accordingly you must use the new operator to create an arrayint[intarray/defines reference to an array intarray new int[ ]/creates the arrayand /sets intarray to refer to it or the equivalent single-statement approachint[intarray new int[ ]the [operator is the sign to the compiler we're naming an array object and not an ordinary variable you can also use an alternative syntax for this operatorplacing it after the name instead of the typeint intarray[new int[ ]/alternative syntax howeverplacing the [after the int makes it clear that the [is part of the typenot the name because an array is an objectits name--intarray in the code above--is reference to an arrayit' not the array itself the array is stored at an address elsewhere in memoryand intarray holds only this address arrays have length fieldwhich you can use to find the sizein bytesof an arrayint arraylength intarray length/find array length remember that this is the total number of bytes occupied by the arraynot the number of data items you have placed in it as in most programming languagesyou can' change the size of an array after it' been created accessing array elements array elements are accessed using square brackets this is similar to how other languages work |
24,788 | intarray[ /get contents of fourth element of array /insert into the eighth cell remember that in javaas in and ++the first element is numbered so that the indices in an array of elements run from to if you use an index that' less than or greater than the size of the array less you'll get the "array index out of boundsruntime error this is an improvement on and ++which don' check for out-of-bounds indicesthus causing many program bugs initialization unless you specify otherwisean array of integers is automatically initialized to when it' created unlike ++this is true even of arrays defined within method (functionif you create an array of objectslike thisautodata[cararray new autodata[ ]thenuntil they're given explicit valuesthe array elements contain the special null object if you attempt to access an array element that contains nullyou'll get the runtime error "null pointer assignment the moral is to make sure you assign something to an element before attempting to access it you can initialize an array of primitive type to something besides using this syntaxint[intarray }perhaps surprisinglythis single statement takes the place of both the reference declaration and the use of new to create the array the numbers within the curly braces are called the initialization list the size of the array is determined by the number of values in this list an array example let' look at some example programs that show how an array can be used we'll start with an old-fashioned procedural versionand then show the equivalent objectoriented approach listing shows the old-fashioned versioncalled array java listing array java /array java /demonstrates java arrays /to run this programc>java arrayapp import java io */for / ///////////////////////////////////////////////////////////////class arrayapp public static void main(string[argsthrows ioexception int[arr/reference arr new int[ ]/make array int nelems /number of items int /loop counter int searchkey/key of item to search for |
24,789 | /insert items arr[ arr[ arr[ arr[ arr[ arr[ arr[ arr[ arr[ nelems /now items in array //for( = <nelemsj++/display items system out print(arr[ ")system out println("")//searchkey /find item with key for( = <nelemsj++/for each elementif(arr[ =searchkey/found itembreak/yesexit before end if( =nelems/at the endsystem out println("can' find searchkey)/yes else system out println("found searchkey)/no //searchkey /delete item with key for( = <nelemsj++/look for it if(arr[ =searchkeybreakfor(int =jk<nelemsk++/move higher ones down arr[karr[ + ]nelems--/decrement size //for( = <nelemsj++/display items system out printarr[ ")system out println("")/end main(/end class arrayapp in this programwe create an array called arrplace data items (kidsnumbersin itsearch for the item with value (the shortstoplouisa)display all the items,remove the item with value (freddywho had dentist appointment)and then display the remaining nine items the output of the program looks like this |
24,790 | found the data we're storing in this array is type int we've chosen primitive type to simplify the coding generally the items stored in data structure consist of several fieldsso they are represented by objects rather than primitive types we'll see an example of this toward the end of this insertion inserting an item into the array is easywe use the normal array syntax arr[ we also keep track of how many items we've inserted into the array with the nelems variable searching the searchkey variable holds the value we're looking for to search for an itemwe step through the arraycomparing searchkey with each element if the loop variable reaches the last occupied cell with no match being foundthen the value isn' in the array appropriate messages are displayed"found or "can' find deletion deletion begins with search for the specified item for simplicity we assume (perhaps rashlythat the item is present when we find itwe move all the items with higher index values down one element to fill in the "holeleft by the deleted elementand we decrement nelems in real programwe' also take appropriate action if the item to be deleted could not be found display displaying all the elements is straightforwardwe step through the arrayaccessing each one with arr[jand displaying it program organization the organization of array java leaves something to be desired there is only one classarrayappand this class has only one methodmain(the program is essentially an old-fashioned procedural program let' see if we can make it easier to understand (among other benefitsby making it more object-oriented we're going to provide gradual introduction to an object-oriented approachusing two steps in the firstwe'll separate the data storage structure (the arrayfrom the rest of the program this remaining part of the program will become user of the structure in the second stepwe'll improve the communication between the storage structure and its user dividing program into classes the array java program essentially consisted of one big method we can reap many benefits by dividing the program into classes what classesthe data storage structure itself is one candidateand the part of the program that uses this data structure is |
24,791 | the programmaking it easier to design and understand (and in real programs to modify and maintainin array java we used an array as data storage structurebut we treated it simply as language element now we'll encapsulate the array in classcalled lowarray we'll also provide class methods by which objects of other classes (the lowarrayapp class in this casecan access the array these methods allow communication between lowarray and lowarrayapp our first design of the lowarray class won' be entirely successfulbut it will demonstrate the need for better approach the lowarray java program in listing shows how it looks listing the lowarray java program /lowarray java /demonstrates array class with low-level interface /to run this programc>java lowarrayapp import java io */for / ///////////////////////////////////////////////////////////////class lowarray private double[ /ref to array public lowarray(int sizea new double[size]/constructor /put element into array public void setelem(int indexdouble valuea[indexvaluepublic double getelem(int indexreturn [index]/end class lowarray /get element from array ///////////////////////////////////////////////////////////////class lowarrayapp public static void main(string[argslowarray arr/reference arr new lowarray( )/create lowarray object int nelems /number of items in array int /loop variable arr setelem( )arr setelem( )/insert items |
24,792 | arr setelem( )arr setelem( )arr setelem( )arr setelem( )arr setelem( )arr setelem( )arr setelem( )nelems /now items in array //for( = <nelemsj++/display items system out print(arr getelem( ")system out println("")//int searchkey /search for data item for( = <nelemsj++/for each elementif(arr getelem( =searchkey/found itembreakif( =nelems/no system out println("can' find searchkey)else /yes system out println("found searchkey)///delete value for( = <nelemsj++/look for it if(arr getelem( = breakfor(int =jk<nelemsk++/move higher ones down arr setelem(karr getelem( + )nelems--/decrement size //for( = <nelemsj++/display items system out printarr getelem( ")system out println("")/end main(/end class lowarrayapp the output from this program is similar to that from array javaexcept that we try to find non-existent key value ( before deleting the item with the key value can' find |
24,793 | in lowarray javawe essentially wrap the class lowarray around an ordinary java array the array is hidden from the outside world inside the classit' privateso only lowarray class methods can access it there are three lowarray methodssetelem(and getelem()which insert and retrieve an elementrespectivelyand constructorwhich creates an empty array of specified size another classlowarrayappcreates an object of the lowarray class and uses it to store and manipulate data think of lowarray as tooland lowarrayapp as user of the tool we've divided the program into two classes with clearly defined roles this is valuable first step in making program object-oriented class used to store data objectsas is lowarray in the lowarray java programis sometimes called container class typicallya container class not only stores the data but provides methods for accessing the dataand perhaps also sorting it and performing other complex actions on it class interfaces we've seen how program can be divided into separate classes how do these classes interact with each othercommunication between classesand the division of responsibility between themare important aspects of object-oriented programming this is especially true when class may have many different users typically class can be used over and over by different users (or the same userfor different purposes for exampleit' possible that someone might use the lowarray class in some other program to store the serial numbers of their traveler' checks the class can handle this just as well as it can store the numbers of baseball players if class is used by many different programmersthe class should be designed so that it' easy to use the way that class user relates to the class is called the class interface because class fields are typically privatewhen we talk about the interface we usually mean the class methodswhat they do and what their arguments are it' by calling these methods that class user interacts with an object of the class one of the important advantages conferred by object-oriented programming is that class interface can be designed to be as convenient and efficient as possible figure is fanciful interpretation of the lowarray interface not so convenient the interface to the lowarray class in lowarray java is not particularly convenient the methods setelem(and getelem(operate on low conceptual levelperforming exactly the same tasks as the [operator in an ordinary java array the class userrepresented by the main(method in the lowarrayapp classends up having to carry out the same low-level operations it did in the non-class version of an array in the array java program the only difference was that it related to setelem(and getelem(instead of the [operator it' not clear that this is an improvement |
24,794 | also notice that there' no convenient way to display the contents of the array somewhat crudelythe lowarrayapp class simply uses for loop and the getelem(method for this purpose we could avoid repeated code by writing separate method for lowarrayapp that it could call to display the array contentsbut is it really the responsibility of the lowarrayapp class to provide this methodthus lowarray java demonstrates how you can divide program into classesbut it really doesn' buy us too much in practical terms let' see how to redistribute responsibilities between the classes to obtain more of the advantages of oop who' responsible for whatin the lowarray java programthe main(routine in the lowarrayapp classthe user of the data storage structure must keep track of the indices to the array for some users of an array who need random access to array elements and don' mind keeping track of the index numbersthis arrangement might make sense for examplesorting an arrayas we'll see in the next can make efficient use of this direct "hands-onapproach howeverin typical program the user of the data storage device won' find access to the array indices to be helpful or relevant in the cardfile program in for exampleif the card data were stored in an arrayand you wanted to insert new cardit would be easier not to have to worry about exactly where in the array it is going to go the higharray java example our next example program shows an improved interface for the storage structure classcalled higharray using this interfacethe class user (the higharrayapp classno longer needs to think about index numbers the setelem(and getelem(methods are gonereplaced by insert()find()and delete(these new methods don' require an index number as an argumentbecause the class takes responsibility for handling index numbers the user of the class (higharrayappis free to concentrate on the what instead of the howwhat' going to be inserteddeletedand accessedinstead of exactly how these activities are carried out figure shows the higharray interface and listing shows the higharray java program |
24,795 | listing the higharray java program /higharray java /demonstrates array class with high-level interface /to run this programc>java higharrayapp import java io */for / ///////////////////////////////////////////////////////////////class higharray private double[ /ref to array private int nelems/number of data items //public higharray(int maxa new double[max]nelems /constructor /create the array /no items yet //public boolean find(double searchkey/find specified value int jfor( = <nelemsj++/for each elementif( [ =searchkey/found itembreak/exit loop before end if( =nelems/gone to endreturn false/yescan' find it else return true/nofound it /end find(//public void insert(double valuea[nelemsvalue/put element into array /insert it |
24,796 | /increment size //public boolean delete(double valueint jfor( = <nelemsj++/look for it ifvalue = [jbreakif( ==nelems/can' find it return falseelse /found it for(int =jk<nelemsk++/move higher ones down [ka[ + ]nelems--/decrement size return true/end delete(//public void display(/displays array contents for(int = <nelemsj++/for each elementsystem out print( [ ")/display it system out println("")///end class higharray ///////////////////////////////////////////////////////////////class higharrayapp public static void main(string[argsint maxsize /array size higharray arr/reference to array arr new higharray(maxsize)/create the array arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )/insert items |
24,797 | arr insert( )arr display()/display items int searchkey /search for item ifarr find(searchkeysystem out println("found searchkey)else system out println("can' find searchkey)arr delete( )arr delete( )arr delete( )/delete items arr display()/end main(/display items again /end class higharrayapp the higharray class is now wrapped around the array in main()we create an array of this class and carry out almost the same operations as in the lowarray java programwe insert itemssearch for an item--one that isn' there--and display the array contents because it' so easywe delete three items ( and instead of oneand finally display the contents again here' the output can' find notice how short and simple main(is the details that had to be handled by main(in lowarray java are now handled by higharray class methods in the higharray classthe find(method looks through the array for the item whose key value was passed to it as an argument it returns true or falsedepending on whether it finds the item or not the insert(method places new data item in the next available space in the array field called nelems keeps track of the number of array cells that are actually filled with data items the main(method no longer needs to worry about how many items are in the array the delete(method searches for the element whose key value was passed to it as an argumentand when it finds itshifts all the elements in higher index cells down one cellthus writing over the deleted valueit then decrements nelems we've also included display(methodwhich displays all the values stored in the array the user' life made easier in lowarray javathe code in main(to search for an item took eight linesin higharray javait takes only one the class userthe higharrayapp classneed not worry about index numbers or any other array details amazinglythe class user does not even need to know what kind of data structure the higharray class is using to store |
24,798 | see the same interface used with somewhat different data structure abstraction the process of separating the how from the what--how an operation is performed inside classas opposed to what' visible to the class user--is called abstraction abstraction is an important aspect of software engineering by abstracting class functionality we make it easier to design programbecause we don' need to think about implementation details at too early stage in the design process the ordered workshop applet imagine an array in which the data items are arranged in order of ascending key valuesthat iswith the smallest value at index and each cell holding value larger than the cell below such an array is called an ordered array when we insert an item into this arraythe correct location must be found for the insertionjust above smaller value and just below larger one then all the larger values must be moved up to make room why would we want to arrange data in orderone advantage is that we can speed up search times dramatically using binary search start the ordered workshop applet you'll see an arrayit' similar to the one in the array workshop appletbut the data is ordered figure shows how this looks in the ordered array we've chosen to not allow duplicates as we saw earlierthis speeds up searching somewhat but slows down insertion figure the ordered workshop applet linear search two search algorithms are available for the ordered workshop appletlinear and binary linear search is the default linear searches operate in much the same way as the searches in the unordered array in the array appletthe red arrow steps alonglooking for match the difference is that in the ordered arraythe search quits if an item with larger key is found try this out make sure the linear radio button is selected then use the find button to search for non-existent value thatif it were presentwould fit somewhere in the middle of the array in figure this might be you'll see that the search terminates when the first item larger than is reachedit' in the figure the algorithm knows there' |
24,799 | try out the ins and del buttons as well use ins to insert an item with key value that will go somewhere in the middle of the existing items you'll see that insertion requires moving all the items with larger key values larger than the item being inserted use the del button to delete an item from the middle of the array deletion works much the same as it did in the array appletshifting items with higher index numbers down to fill in the hole left by the deletion in the ordered arrayhoweverthe deletion algorithm can quit partway through if it doesn' find the itemjust as the search routine can binary search the payoff for using an ordered array comes when we use binary search this kind of search is much faster than linear searchespecially for large arrays the guess- -number game binary search uses the same approach you did as kid (if you were smartto guess number in the well-known children' guessing game in this gamea friend asks you to guess number she' thinking of between and when you guess numbershe'll tell you one of three thingsyour guess is larger than the number she' thinking ofit' smalleror you guessed correctly to find the number in the fewest guessesyou should always start by guessing if she says your guess is too lowyou deduce the number is between and so your next guess should be (halfway between and if she says it' too highyou deduce the number is between and so your next guess should be each guess allows you to divide the range of possible values in half finallythe range is only one number longand that' the answer notice how few guesses are required to find the number if you used linear searchguessing first then then and so onit would take youon the average guesses to find the number in binary search each guess divides the range of possible values in halfso the number of quesses required is far fewer table shows game session when the number to be guessed is table guessing number step number number guessed result range of possible values - too high - too low - too high - too low - |
Subsets and Splits