Sei sulla pagina 1di 17

Top Data Structure interview questions and answers are below

Questions : What is data structure? 1 Answers : A data structure is a way of organizing data that considers not only the items stored, 1

but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data.

Questions List out the areas in which data structures are applied extensively? :2 Answers : =>Compiler Design, 2 => Operating System, => Database Management System, => Statistical analysis package, => Numerical Analysis, => Graphics, => Artificial Intelligence, => Simulation Questions What are the major data structures used in the following areas : RDBMS, :3 Network data model & Hierarchical data model. Answers : =>RDBMS - Array (i.e. Array of structures) 3 =>Network data model Graph =>Hierarchical data model Trees Questions If you are using C language to implement the heterogeneous linked list, :4 what pointer type will you use? Answers : The heterogeneous linked list contains different data types in its nodes and we need 4 a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type. . Questions Minimum number of queues needed to implement the priority queue? :5 Answers : Two. One queue is used for actual storing of data and another for storing priorities. . 5 Questions What is the data structures used to perform recursion? :6 Answers : Stack. Because of its LIFO (Last In First Out) property it remembers its caller so 6 knows whom to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls. Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, explicit stack is to be used. Questions What are the notations used in Evaluation of Arithmetic Expressions using :7 prefix and postfix forms? Answers : Polish and Reverse Polish notations. 7 Questions Convert the expression ((A + B) * C (D E) ^ (F + G)) to equivalent :8 Prefix and Postfix notations. Answers : Prefix Notation: ^ - * +ABC - DE + FG Postfix Notation: AB + C * DE - - FG + ^ 8 Questions Sorting is not possible by using which of the following methods? :9 (a) Insertion (b) Selection (c) Exchange (d) Deletion

Answers : (d) Deletion. 9 Using insertion we can perform insertion sort, using selection we can perform selection sort, using exchange we can perform the bubble sort (and other similar sorting methods). But no sorting method can be done just using deletion. Questions What are the methods available in storing sequential files ? : 10 Answers : a>Straight merging, 10 b> Natural merging, c> Polyphase sort, d> Distribution of Initial runs. Questions List out few of the Application of tree data-structure? : 11 Answers : a>The manipulation of Arithmetic expression, 11 b> Symbol Table construction, c> Syntax analysis. Questions List out few of the applications that make use of Multilinked Structures? : 12 Answers : a> Sparse matrix, 12 b> Index generation. Questions 15. In tree construction which is the suitable efficient data structure? : 13 (a) Array (b) Linked list (c) Stack (d) Queue (e) none Answers : (b) Linked list 13 Questions What is a spanning Tree?Does the minimum spanning tree of a graph give : 14 the shortest distance between any 2 specified nodes? Answers : A spanning tree is a tree associated with a network. All the nodes of the graph 14 appear on the tree once. A minimum spanning tree is a spanning tree organized so that the total edge weight between nodes is minimized. No. minimum spanning tree of a graph give the shortest distance between any 2 specified node Minimal spanning tree assures that the total weight of the tree is kept at its minimum. But it doesnt mean that the distance between any two nodes involved in the minimum-spanning tree is minimum. Questions Which is the simplest file structure? : 15 (a) Sequential (b) Indexed (c) Random Answers : (a) Sequential 15 Questions Whether Linked List is linear or Non-linear data structure? : 16 Answers : According to Access strategies Linked list is a linear one. 16 According to Storage Linked List is a Non-linear one. Questions 28. Of the following tree structure, which is, efficient considering space and : 17 time complexities? (a) Incomplete Binary Tree (b) Complete Binary Tree (c) Full Binary Tree Answers : (b) Complete Binary Tree. 17

By the method of elimination: Full binary tree loses its nature when operations of insertions and deletions are done. For incomplete binary trees, extra storage is required and overhead of NULL node checking takes place. So complete binary tree is the better one since the property of complete binary tree is maintained even after operations like additions and deletions are done on it. Questions In RDBMS, what is the efficient data structure used in the internal storage : 18 representation? Answers : B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes 18 searching easier. This corresponds to the records that shall be stored in leaf nodes. Questions 25. What are the types of Collision Resolution Techniques and the methods : 19 used in each of the type? Answers : a> Open addressing (closed hashing), The methods used include: 19 Overflow block, b> Closed addressing (open hashing) The methods used include: Linked list, Binary tree Questions Classify the Hashing Functions based on the various methods by which the : 20 key value is found. Answers : => Subtraction method, 20 => Modulo-Division method, =>Digit-Extraction method, => Mid-Square method, => Folding method, => Pseudo-random method. => Direct method, Questions In an AVL tree, at what condition the balancing is to be done? : 21 Answers : If the pivotal value (or the Height factor) is greater than 1 or less than 1. 21 What is mean by d-queue ? Answer:D-queue stands for double ended queue. It is a abstract data structure that implements a queue for which elements can be added to front or rear and the elements can be removed from the rear or front. It is also called head-tail linked list :Example of linear and non-linear data structures ? Answer:The data structure is said to be a Linear data structure if its elements are in sequence and form a linear list.Ex. Arrays, Stacks, Queues,Linked Lists. If the elements of data structure do not form a sequence or a linear list then that type of data structure is called as Non-Linear data structure.Ex. Trees, BST(Binary Search Trees) etc. How to find the number of possible tree in the given tree . Answer: The number of possible tree = (2 power of n) - n. For example:A tree contain three node.So if n=3,the possible number of trees = 8 - 3 = 5. What is hashing Answer:Hashing is a way retrieving records from memory in faster way. Record is inserted into memory by using hash function(division, midsqure,folding,digit analysis)and also records are retrieved using same hash function.

What is AVL tree?

Answer:Avl tree is self binary tree in which balancing factor lie between the -1 to 1.It is also known as self balancing tree.

Operating Systems interview questions and answers are below


Questions : Explain the concept of Reentrancy. ? 1 Answers : It is a useful, memory-saving technique for multiprogrammed timesharing systems. 1

A Reentrant Procedure is one in which multiple users can share a single copy of a program during the same period. Reentrancy has 2 key aspects: The program code cannot modify itself, and the local data for each user process must be stored separately. Thus, the permanent part is the code, and the temporary part is the pointer back to the calling program and local variables used by that program. Each execution instance is called activation. It executes the code in the permanent part, but has its own copy of local variables/parameters. The temporary part associated with each activation is the activation record. Generally, the activation record is kept on the stack. Note: A reentrant procedure can be interrupted and called by an interrupting program, and still execute correctly on returning to the procedure.

Questions Explain Belady's Anomaly. :2 Answers : Also called FIFO anomaly. Usually, on increasing the number of frames allocated to a 2 process' virtual memory, the process execution is faster, because fewer page faults occur. Sometimes, the reverse happens, i.e., the execution time increases even when more frames are allocated to the process. This is Belady's Anomaly. This is true for certain page reference patterns.

Questions What is a binary semaphore? What is its use? :3 Answer : 3 A binary semaphore is one, which takes only 0 and 1 as values. They are used to implement mutual exclusion and synchronize concurrent processes. Questions What is thrashing? :4 Answer : 4 It is a phenomenon in virtual memory schemes when the processor spends most of its time swapping pages, rather than executing instructions. This is due to an inordinate number of page faults. Questions List the Coffman's conditions that lead to a deadlock. :5 Answers : ==> Mutual Exclusion : Only one process may use a critical resource at a time. 5 ==> Hold and Wait : A process may be allocated some resources while waiting for others. ==> No Pre-emption : No resource can be forcible removed from a process holding it. ==> Circular Wait : A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain. Questions What are short-term, long-term and medium-term scheduling? :6 Answers : Long term scheduler determines which programs are admitted to the system for 6 processing. It controls the degree of multiprogramming. Once admitted, a job becomes a process. Medium term scheduling is part of the swapping function. This relates to processes that are in a blocked or suspended state. They are swapped out of real-memory until they are ready to execute. The swapping-in decision is based on memory-

management criteria. Short term scheduler, also know as a dispatcher executes most frequently, and makes the finest-grained decision of which process should execute next. This scheduler is invoked whenever an event occurs. It may lead to interruption of one process by preemption. Questions What are turnaround time and response time? :7 Answers : Turnaround time is the interval between the submission of a job and its completion. 7 Response time is the interval between submission of a request, and the first response to that request. Questions What are the typical elements of a process image? :8 Answers : ==> User data : Modifiable part of user space. May include program data, user 8 stack area, and programs that may be modified. ==> User program : The instructions to be executed. ==> System Stack : Each process has one or more LIFO stacks associated with it. Used to store parameters and calling addresses for procedure and system calls. ==> Process control Block (PCB) : Info needed by the OS to control processes. Questions What is the Translation Lookaside Buffer (TLB)? :9 Answers : In a cached system, the base addresses of the last few referenced pages is 9 maintained in registers called the TLB that aids in faster lookup. TLB contains those page-table entries that have been most recently used. Normally, each virtual memory reference causes 2 physical memory accesses-- one to fetch appropriate page-table entry, and one to fetch the desired data. Using TLB in-between, this is reduced to just one physical memory access in cases of TLB-hit. Questions What is the resident set and working set of a process? : 10 Answers : Resident set is that portion of the process image that is actually in real-memory at a 10 particular instant. Working set is that subset of resident set that is actually needed for execution. (Relate this to the variable-window size method for swapping techniques.) Questions When is a system in safe state? : 11 Answers : The set of dispatchable processes is in a safe state if there exists at least one 11 temporal order in which all processes can be run to completion without resulting in a deadlock. Questions What is cycle stealing? : 12 Answers : We encounter cycle stealing in the context of Direct Memory Access (DMA). Either 12 the DMA controller can use the data bus when the CPU does not need it, or it may force the CPU to temporarily suspend operation. The latter technique is called cycle stealing. Note that cycle stealing can be done only at specific break points in an instruction cycle. Questions What is meant by arm-stickiness? : 13 Answers : If one or a few processes have a high access rate to data on one track of a storage 13 disk, then they may monopolize the device by repeated requests to that track. This generally happens with most common device scheduling algorithms (LIFO, SSTF, CSCAN, etc). High-density multisurface disks are more likely to be affected by this than low density ones.

Questions What are the stipulations of C2 level security? : 14 Answers : C2 level security provides for: 14 ==> Discretionary Access Control ==> Identification and Authentication ==> Auditing ==> Resource reuse Questions What is busy waiting? : 15 Answers : The repeated execution of a loop of code while waiting for an event to occur is called 15 busy-waiting. The CPU is not engaged in any real productive activity during this period, and the process does not progress toward completion. Questions Explain the popular multiprocessor thread-scheduling strategies. : 16 Answers : ==> Load Sharing : Processes are not assigned to a particular processor. A global 16 queue of threads is maintained. Each processor, when idle, selects a thread from this queue. Note that load balancing refers to a scheme where work is allocated to processors on a more permanent basis. ==>Gang Scheduling: A set of related threads is scheduled to run on a set of processors at the same time, on a 1-to-1 basis. Closely related threads / processes may be scheduled this way to reduce synchronization blocking, and minimize process switching. Group scheduling predated this strategy. ==>Dedicated processor assignment: Provides implicit scheduling defined by assignment of threads to processors. For the duration of program execution, each program is allocated a set of processors equal in number to the number of threads in the program. Processors are chosen from the available pool. ==>Dynamic scheduling: The number of thread in a program can be altered during the course of execution. Questions When does the condition 'rendezvous' arise? : 17 Answers : In message passing, it is the condition in which, both, the sender and receiver are 17 blocked until the message is delivered. Questions What is a trap and trapdoor? : 18 Answers : Trapdoor is a secret undocumented entry point into a program used to grant access 18 without normal methods of access authentication. A trap is a software interrupt, usually the result of an error condition. Questions What are local and global page replacements? : 19 Answers : Local replacement means that an incoming page is brought in only to the relevant 19 process' address space. Global replacement policy allows any page frame from any process to be replaced. The latter is applicable to variable partitions model only. Questions Define latency, transfer and seek time with respect to disk I/O. : 20 Answers : Seek time is the time required to move the disk arm to the required track. Rotational 20 delay or latency is the time it takes for the beginning of the required sector to reach the head. Sum of seek time (if any) and latency is the access time. Time taken to actually transfer a span of data is transfer time. Questions Describe the Buddy system of memory allocation. : 21

Answers : Free memory is maintained in linked lists, each of equal sized blocks. Any such block 21 is of size 2^k. When some memory is required by a process, the block size of next higher order is chosen, and broken into two. Note that the two such pieces differ in address only in their kth bit. Such pieces are called buddies. When any used block is freed, the OS checks to see if its buddy is also free. If so, it is rejoined, and put into the original free-block linked-list. Questions What is time-stamping? : 22 Answers : It is a technique proposed by Lamport, used to order events in a distributed system 22 without the use of clocks. This scheme is intended to order events consisting of the transmission of messages. Each system 'i' in the network maintains a counter Ci. Every time a system transmits a message, it increments its counter by 1 and attaches the time-stamp Ti to the message. When a message is received, the receiving system 'j' sets its counter Cj to 1 more than the maximum of its current value and the incoming time-stamp Ti. At each site, the ordering of messages is determined by the following rules: For messages x from site i and y from site j, x precedes y if one of the following conditions holds....(a) if Ti<j.<="" p=""> Questions How are the wait/signal operations for monitor different from those for : 23 semaphores? Answers : If a process in a monitor signal and no task is waiting on the condition variable, the 23 signal is lost. So this allows easier program design. Whereas in semaphores, every operation affects the value of the semaphore, so the wait and signal operations should be perfectly balanced in the program. Questions In the context of memory management, what are placement and : 24 replacement algorithms? Answers : Placement algorithms determine where in available real-memory to load a program. 24 Common methods are first-fit, next-fit, best-fit. Replacement algorithms are used when memory is full, and one process (or part of a process) needs to be swapped out to accommodate a new program. The replacement algorithm determines which are the partitions to be swapped out. Questions In loading programs into memory, what is the difference between load-time : 25 dynamic linking and run-time dynamic linking? Answer : For load-time dynamic linking: Load module to be loaded is read into memory. Any 25 reference to a target external module causes that module to be loaded and the references are updated to a relative address from the start base address of the application module. With run-time dynamic loading: Some of the linking is postponed until actual reference during execution. Then the correct module is loaded and linked. Questions What are demand- and pre-paging? : 26 Answer : With demand paging, a page is brought into memory only when a location on that 26 page is actually referenced during execution. With pre-paging, pages other than the one demanded by a page fault are brought in. The selection of such pages is done based on common access patterns, especially for secondary memory devices. Questions Paging a memory management function, while multiprogramming a : 27 processor management function, are the two interdependent? Answers : Yes. 27 Questions What is page cannibalizing? : 28 Answer : Page swapping or page replacements are called page cannibalizing.

28 Questions What has triggered the need for multitasking in PCs? : 29 Answer : ==> Increased speed and memory capacity of microprocessors together with the 29 support fir virtual memory and ==> Growth of client server computing Questions : 30 Answer : 30 What are the four layers that Windows NT have in order to achieve independence? ==> Hardware abstraction layer ==> Kernel ==> Subsystems ==> System Services.

Questions What is SMP? : 31 Answer : To achieve maximum efficiency and reliability a mode of operation known as 31 symmetric multiprocessing is used. In essence, with SMP any process or threads can be assigned to any processor. Questions What are the key object oriented concepts used by Windows NT? : 32 Answer : ==> Encapsulation 32 ==> Object class and instance Questions Is Windows NT a full blown object oriented operating system? Give reasons. : 33 Answer : No Windows NT is not so, because its not implemented in object oriented language 33 and the data structures reside within one executive component and are not represented as objects and it does not support object oriented capabilities Questions What is a drawback of MVT? : 34 Answer : It does not have the features like 34 ==> ability to support multiple processors ==> virtual storage ==> source level debugging Questions What is process spawning? : 35 Answer : When the OS at the explicit request of another process creates a process, this action 35 is called process spawning Questions How many jobs can be run concurrently on MVT? : 36 Answer : 15 jobs 36 Questions List out some reasons for process termination. : 37 Answer : ==> Normal completion 37 ==> Time limit exceeded ==> Memory unavailable ==> Bounds violation ==> Protection error ==> Arithmetic error ==> Time overrun ==> I/O failure ==> Invalid instruction ==> Privileged instruction ==> Data misuse ==> Operator or OS intervention ==> Parent termination

Questions What are the reasons for process suspension? : 38 Answer : ==> swapping 38 ==> interactive user request ==> timing ==> parent process request Questions What is process migration? : 39 Answer : It is the transfer of sufficient amount of the state of process from one machine to the 39 target machine Questions What is mutant? : 40 Answer : In Windows NT a mutant provides kernel mode or user mode mutual exclusion with 40 the notion of ownership. Questions What is an idle thread? : 41 Answer : The special thread a dispatcher will execute when no ready thread is found 41 Questions What is FtDisk? : 42 Answer : It is a fault tolerance disk driver for Windows NT. 42 Questions What are the possible threads a thread can have? : 43 Answer : ==> Ready 43 ==> Standby ==> Running ==> Waiting ==> Transition ==> Terminated. Questions What are rings in Windows NT? : 44 Answer : Windows NT uses protection mechanism called rings provides by the process to 44 implement separation between the user mode and kernel mode. Questions What is Executive in Windows NT? : 45 Answer : In Windows NT, executive refers to the operating system code that runs in kernel 45 mode. Questions What are the sub-components of I/O manager in Windows NT? : 46 Answer : ==> Network redirector/ Server 46 ==> Cache manager. ==> File systems ==> Network driver ==> Device driver Questions What are DDks? Name an operating system that includes this feature. : 47 Answer : DDks are device driver kits, which are equivalent to SDKs for writing device drivers. 47 Windows NT includes DDks. Questions What level of security does Windows NT meets? : 48 Answer : C2 level security. 48

1 .In a selectionsort of n elements, how many times is the swap function called in the complete execution of the algorithm? A. 1 B. n - 1 C. n log n D. n^2 Solution: B. n-1

2 .Selectionsort and quicksort both fall into the same category of sorting algorithms. What is this category? * * * * A. O(n log n) sorts B. Divide-and-conquer sorts C. Interchange sorts D. Average time is quadratic.

Solution: C.Interchange sorts reason:Selection sort is not O(n log n) and not a Divide-conquer sort too and Average time of quicksort is not quadratic. 3 . Suppose that a selectionsort of 100 items has completed 42 iterations of the main loop. How many items are now guaranteed to be in their final spot (never to be moved again)? * * * * A. 21 B. 41 C. 42 D. 43

Solution: C. 42 4 .Suppose we are sorting an array of ten integers using a some quadratic sorting algorithm. After four iterations of the algorithm's main loop, the array elements are ordered as shown here: 1234506789 Which statement is correct? (Note: Our selection sort picks largest items first.) * A. The algorithm might be either selection sort or insertion sort. * B. The algorithm might be selectionsort, but could not be insertionsort. * C. The algorithm might be insertionsort, but could not be selectionsort.

* D. The algorithm is neither selectionsort nor insertionsort. Solution: C. The algorithm might be insertion sort, but could not be selection sort. 5 .Suppose we are sorting an array of eight integers using a some quadratic sorting algorithm. After four iterations of the algorithm's main loop, the array elements are ordered as shown here: 24578136 Which statement is correct? (Note: Our selectionsort picks largest items first.) * * * * A. The algorithm might be either selectionsort or insertionsort. B. The algorithm might be selectionsort, but it is not insertionsort. C. The algorithm is not selectionsort, but it might be insertionsort. D. The algorithm is neither selectionsort nor insertionsort.

Solution: C. The algorithm is not selectionsort, but it might be insertionsort. 6 .When is insertionsort a good choice for sorting an array? * * * * A. Each component of the array requires a large amount of memory. B. Each component of the array requires a small amount of memory. C. The array has only a few items out of place. D. The processor speed is fast.

Solution: C. The array has only a few items out of place. 7 What is the worst-case time for mergesort to sort an array of n elements? * * * * A. O(log n) B. O(n) C. O(n log n) D. O(n^2)

Solution : C. O(n log n) 8 What is the worst-case time for quicksort to sort an array of n elements? * * * * A. O(log n) B. O(n) C. O(n log n) D. O(n^2)

Solution: D. O(n^2) 9 .Mergesort makes two recursive calls. Which statement is true after these recursive calls finish, but before the merge step? * * * * A. The array elements form a heap. B. Elements in each half of the array are sorted amongst themselves. C. Elements in the first half of the array are less than or equal to elements in the second half of the array. D. None of the above.

Solution: B. Elements in each half of the array are sorted amongst themselves.

10 .Suppose we are sorting an array of eight integers using quicksort, and we have just finished the first partitioning with the array looking like this: 2 5 1 7 9 12 11 10 Which statement is correct? * * * * A. The pivot could be either the 7 or the 9. B. The pivot could be the 7, but it is not the 9. C. The pivot is not the 7, but it could be the 9. D. Neither the 7 nor the 9 is the pivot.

Solution: A. The pivot could be either the 7 or the 9. 11 .What is the worst-case time for heapsort to sort an array of n elements? * A. O(log n) * B. O(n) * C. O(n log n) * D. O(n^2) Solution: C. O(n log n) 12.Suppose you are given a sorted list of N elements followed by f(N) randomly ordered elements.How would you sort the entire list if * A. f(N)=O(1) * B. f(N)=O(logN) * C. f(N)=O(N^1/2) * D. How large can f(N) be for the entire list still to be sortable in O(N) time? Solution: A. f(N)=O(1) In this case insertion sort would be the best ,giving the time complexity of O(N) B. f(N)=O(log N) Merge sort is the best option with a time complexity of O(N) C.f(N)=O(N^1/2) Merge sort is the best option with a time complexity of O(N) D.complexity = f(N)log f(N) + N +f(N) Clearly f(N) is O(N) for the complexity to be of O(N) Now O(N) is an over estimate on the upper bound of f(N) ,which is quite clear from the first term in the above expression. Now let f(N) is of the form k.N^(1/p ).Then with some simplification we get f(N)log(f(N)) is O(N ^(2/p)) and now to restrict the whole expression to O(N) we need to restrict p to p >= 2 But f(N)is O(N^(1/p)) which means f(N) can at most be of size N^1/2 . 13.Prove that any algorithm that find an element X in a sorted list of N elements requires Omega(log N) comparisons. Solution:The search essentially becomes a search for X in a binary decision tree and this requires Omega(log N) comparisons.

14.Prove that sorting N elements with integer keys in the range 1 < Key < M takes O(M + N) time using bucket sort. Solution: Putting the elements in to their corresponding buckets is of O(N).Then iteration of the buckets and printing the corresponding keys as many times as their frequency is of O(M+N).Hence the total complexity. 15.Suppose you have an array of N elements,containing only 2 distinct keys, true and false.Give an O(N) algorithm to sort the array. Solution:Use bucket sort with 2 buckets. 16.Prove that any comparison based algorithm to sort 4 elements requires at least 3 comparisons and at the max comparisons Solution:The binary decision tree has maximum distance of 3 and a maximum distance of 5 ,from the root to the leaf.As each edge corresponds to a comparison,we need minimum of 3 and maximum of 5 comparisons to sort 4 elements. 17. In how many ways can 2 sorted arrays of combined size N be merged? Solution:Still up for debate.Any answers? :) 18.Show that binary insertion may reasonably be expected to be an O(n log n) sort. Solution:Binary insertion sort employs binary search to find the right place to insert new elements, and therefore performs ceil (log(n!)) comparisons in the worst case, which is (n log n). The algorithm as a whole still takes (n2) time on average due to the series of swaps required for each insertion, and since it always uses binary search, the best case is no longer (n) but (n log n).

19.You are given two sets of numbers Xi and Yj , where i and j run from 1 to N. Devise an algorithm to find the M largest values of Xi Yj . This algorithm should not be quadratic in N, though it is permitted to be quadratic in M. You should regard N as being of the order of 20,000 and M as being of the order of 1,000. Solution:Use an order-statistic algorithm to find the Mth largest number in X,partition around that number and sort the M largest numbers.Repeat this for Y but sorting the M smallest numbers.This can be done in O(N+M log(M))Now with each of these sub-arrays having M elements,find the difference between each element of X and Y.We have M difference elements for each Xi in sorted order and in total M^2 differences.Use merge sort repeatedly to merge these portions .This is of complexity M^2.Hence the procedure. 20.If 1024 numbers are drawn randomly in the range 0127 and sorted by binary insertion, about how many compares would you expect? Solution:We have 3 comparisons coming in to the picture a<b, a>b, a=b.The overall number of comparisons won't change and it is still of the O(N log N). strictly speaking log(N!) comparisons. 1 .In a selectionsort of n elements, how many times is the swap function called in the complete execution of the algorithm? A. 1 B. n - 1 C. n log n D. n^2 Solution: B. n-1

2 .Selectionsort and quicksort both fall into the same category of sorting algorithms. What is this category? * * * * A. O(n log n) sorts B. Divide-and-conquer sorts C. Interchange sorts D. Average time is quadratic.

Solution: C.Interchange sorts reason:Selection sort is not O(n log n) and not a Divide-conquer sort too and Average time of quicksort is not quadratic. 3 . Suppose that a selectionsort of 100 items has completed 42 iterations of the main loop. How many items are now guaranteed to be in their final spot (never to be moved again)? * * * * A. 21 B. 41 C. 42 D. 43

Solution: C. 42 4 .Suppose we are sorting an array of ten integers using a some quadratic sorting algorithm. After four iterations of the algorithm's main loop, the array elements are ordered as shown here: 1234506789 Which statement is correct? (Note: Our selection sort picks largest items first.) * * * * A. The algorithm might be either selection sort or insertion sort. B. The algorithm might be selectionsort, but could not be insertionsort. C. The algorithm might be insertionsort, but could not be selectionsort. D. The algorithm is neither selectionsort nor insertionsort.

Solution: C. The algorithm might be insertion sort, but could not be selection sort. 5 .Suppose we are sorting an array of eight integers using a some quadratic sorting algorithm. After four iterations of the algorithm's main loop, the array elements are ordered as shown here: 24578136 Which statement is correct? (Note: Our selectionsort picks largest items first.) * * * * A. The algorithm might be either selectionsort or insertionsort. B. The algorithm might be selectionsort, but it is not insertionsort. C. The algorithm is not selectionsort, but it might be insertionsort. D. The algorithm is neither selectionsort nor insertionsort.

Solution: C. The algorithm is not selectionsort, but it might be insertionsort. 6 .When is insertionsort a good choice for sorting an array? * A. Each component of the array requires a large amount of memory.

* B. Each component of the array requires a small amount of memory. * C. The array has only a few items out of place. * D. The processor speed is fast. Solution: C. The array has only a few items out of place. 7 What is the worst-case time for mergesort to sort an array of n elements? * * * * A. O(log n) B. O(n) C. O(n log n) D. O(n^2)

Solution : C. O(n log n) 8 What is the worst-case time for quicksort to sort an array of n elements? * * * * A. O(log n) B. O(n) C. O(n log n) D. O(n^2)

Solution: D. O(n^2) 9 .Mergesort makes two recursive calls. Which statement is true after these recursive calls finish, but before the merge step? * * * * A. The array elements form a heap. B. Elements in each half of the array are sorted amongst themselves. C. Elements in the first half of the array are less than or equal to elements in the second half of the array. D. None of the above.

Solution: B. Elements in each half of the array are sorted amongst themselves. 10 .Suppose we are sorting an array of eight integers using quicksort, and we have just finished the first partitioning with the array looking like this: 2 5 1 7 9 12 11 10 Which statement is correct? * * * * A. The pivot could be either the 7 or the 9. B. The pivot could be the 7, but it is not the 9. C. The pivot is not the 7, but it could be the 9. D. Neither the 7 nor the 9 is the pivot.

Solution: A. The pivot could be either the 7 or the 9. 11 .What is the worst-case time for heapsort to sort an array of n elements? * * * * A. O(log n) B. O(n) C. O(n log n) D. O(n^2)

Solution: C. O(n log n) 12.Suppose you are given a sorted list of N elements followed by f(N) randomly ordered elements.How would you sort the entire list if * A. f(N)=O(1) * B. f(N)=O(logN) * C. f(N)=O(N^1/2) * D. How large can f(N) be for the entire list still to be sortable in O(N) time? Solution: A. f(N)=O(1) In this case insertion sort would be the best ,giving the time complexity of O(N) B. f(N)=O(log N) Merge sort is the best option with a time complexity of O(N) C.f(N)=O(N^1/2) Merge sort is the best option with a time complexity of O(N) D.complexity = f(N)log f(N) + N +f(N) Clearly f(N) is O(N) for the complexity to be of O(N) Now O(N) is an over estimate on the upper bound of f(N) ,which is quite clear from the first term in the above expression. Now let f(N) is of the form k.N^(1/p ).Then with some simplification we get f(N)log(f(N)) is O(N ^(2/p)) and now to restrict the whole expression to O(N) we need to restrict p to p >= 2 But f(N)is O(N^(1/p)) which means f(N) can at most be of size N^1/2 . 13.Prove that any algorithm that find an element X in a sorted list of N elements requires Omega(log N) comparisons. Solution:The search essentially becomes a search for X in a binary decision tree and this requires Omega(log N) comparisons. 14.Prove that sorting N elements with integer keys in the range 1 < Key < M takes O(M + N) time using bucket sort. Solution: Putting the elements in to their corresponding buckets is of O(N).Then iteration of the buckets and printing the corresponding keys as many times as their frequency is of O(M+N).Hence the total complexity. 15.Suppose you have an array of N elements,containing only 2 distinct keys, true and false.Give an O(N) algorithm to sort the array. Solution:Use bucket sort with 2 buckets. 16.Prove that any comparison based algorithm to sort 4 elements requires at least 3 comparisons and at the max comparisons Solution:The binary decision tree has maximum distance of 3 and a maximum distance of 5 ,from the root to the leaf.As each edge corresponds to a comparison,we need minimum of 3 and maximum of 5 comparisons to sort 4 elements. 17. In how many ways can 2 sorted arrays of combined size N be merged? Solution:Still up for debate.Any answers? :)

18.Show that binary insertion may reasonably be expected to be an O(n log n) sort. Solution:Binary insertion sort employs binary search to find the right place to insert new elements, and therefore performs ceil (log(n!)) comparisons in the worst case, which is (n log n). The algorithm as a whole still takes (n2) time on average due to the series of swaps required for each insertion, and since it always uses binary search, the best case is no longer (n) but (n log n).

19.You are given two sets of numbers Xi and Yj , where i and j run from 1 to N. Devise an algorithm to find the M largest values of Xi Yj . This algorithm should not be quadratic in N, though it is permitted to be quadratic in M. You should regard N as being of the order of 20,000 and M as being of the order of 1,000. Solution:Use an order-statistic algorithm to find the Mth largest number in X,partition around that number and sort the M largest numbers.Repeat this for Y but sorting the M smallest numbers.This can be done in O(N+M log(M))Now with each of these sub-arrays having M elements,find the difference between each element of X and Y.We have M difference elements for each Xi in sorted order and in total M^2 differences.Use merge sort repeatedly to merge these portions .This is of complexity M^2.Hence the procedure. 20.If 1024 numbers are drawn randomly in the range 0127 and sorted by binary insertion, about how many compares would you expect? Solution:We have 3 comparisons coming in to the picture a<b, a>b, a=b.The overall number of comparisons won't change and it is still of the O(N log N). strictly speaking log(N!) comparisons.

Potrebbero piacerti anche