37
1. This problem is about a simple data structure : (a) This data structure is used to match balanced parentheses expressions and is often hardwired in processors. Identify it. Solution: stack recursive (b) List the operations (excluding create / destroy) of this data structure with one-line description each. Operations: Void push(string &)-which takes a string String pop()-which returns the last push and removes it from the system Bool empty()-checks whether stack is empty or not. (c) Outline the implementation of this data structure using a deque as a container. Assume that the dequeue supports the operations – Push Front(), Push Back(), Pop Front(), and Pop Back() where the dequeue operations have the usual meaning. A dequeue is a homogeneous list in which elements can be added or inserted (called push operation) and deleted or removed from both the ends (which is called pop operation). ie; we can add a new element at the rear or front end and also we can remove an element from both front and rear end. Hence it is called Double Ended Queue. INSERT AN ELEMENT AT THE PUSH BACK() 1. Input the DATA to be inserted 2. If ((left == 0 && right == MAX–1) || (left == right + 1)) (a) Display “Queue Overflow” (b) Exit 3. If (left == –1) (a) left = 0 (b) rig ht = 0 4. Else (a) if (right == MAX –1) (i) left = 0

Assignment 2week

Embed Size (px)

Citation preview

1. This problem is about a simple data structure:

(a) This data structure is used to match balancedparentheses expressions and is often hardwired in processors.Identify it. Solution: stack recursive (b) List the operations (excluding create / destroy) of thisdata structure with one-line description each. Operations: Void push(string &)-which takes a string String pop()-which returns the last push andremoves it from the system Bool empty()-checkswhether stack is empty or not. (c) Outline the implementation of this data structure usinga deque as a container. Assume that the dequeue supports theoperations – Push Front(), Push Back(), Pop Front(), and PopBack() where the dequeue operations have the usual meaning.

A dequeue is a homogeneous list in which elements can be added or inserted (called push operation) and deleted or removed from both the ends (which is called pop operation). ie; we can add a new element at the rear or front end and also we can remove an element from both front and rear end. Hence it is called Double Ended Queue.

INSERT AN ELEMENT AT THE PUSH BACK()1. Input the DATA to be inserted 2. If ((left == 0 && right == MAX–1) || (left == right +1))

(a) Display “Queue Overflow” (b) Exit 3. If (left == –1) (a) left = 0 (b) right = 04. Else (a) if (right == MAX –1) (i) left = 0

(b) else (i) right = right+1 5. Q[right] = DATA 6. Exit INSERT AN ELEMENT AT THE PUSHFRONT() 1. Input the DATA to beinserted 2. If ((left == 0 && right == MAX–1) || (left == right+1))

(a) Display “Queue Overflow” (b) Exit THE QUEUES 79 3. If (left == – 1)(a) Left = 0 (b) Right = 04. Else (a) if (left == 0) (i) left = MAX – 1 (b) else (i) left = left – 1 5. Q[left] = DATA 6. ExitALGORITHMS FOR DELETING AN ELEMENT Let Q be the array of MAX elements. front (or left) andrear (or right) are two array index (pointers), where theaddition and deletion of elements occurred. DATA willcontain the element just deleted.Pop Back()1. If (left == – 1)(a) Display “Queue Underflow” (b) Exit 2. DATA = Q [right] 3. If (left == right) (a) left = – 1 (b) right = – 1 4. Else (a) if(right == 0) (i) right = MAX-1 (b) else (i) right =right-1 5. ExitPop Front()1. If (left == – 1)

(a) Display “Queue Underflow” (b) Exit 2. DATA = Q [left] 3. If(left == right) (a) left = – 1 (b) right = – 1 4. Else (a) if (left == MAX-1) (i) left = 0 (b) Else (i) left =left +1 5.Exit

(d) Explain the use of this data structure to implement Undo-Redo feature in a text editor like WORD.

An undo/redo feature is a "must-have" in today's applications. It is very easy to implement. Throughout this article, how an undo/redo buffer works using the example of an RPN calculator stack. An undo/redo buffer primarily implements three methods:

1. Do 2. Undo 3. Redo

The Do Method

This method records the current state, and this is very important, before the action takes place, as illustrated bythis diagram:

2. (a) Design a suitable data structure to represent arational polynomial P of order n in a single rationalvariable x.(b) Using your representation, explain how would you performthe following operations and analyse the complexity of everyoperation. P & Q are polynomials and x is a given rationalvalue.• Evaluate P for given x.

A polynomial in the variable x over an algebraic field F is a representation of a functionA(x)

as a formal sum:

• Add P with Q.

There are a variety of operations we might wish to define for polynomials. For polynomial addition, if P(x) and Q(x) are polynomials of degree-bound n, we say that their sum is a

polynomial C(x), also of degree-bound n, such that C(x) = P(x) + Q(x) for all x in the underlying field. That is, ifP(x) =∑i=0

n-1pixiAndQ(x) =∑i=0

n-1qixi

ThenC(x) =∑i=0

n-1cixiwhere cj = pi + qi for i = 0, 1,..., n - 1. For example, if we have the polynomials P(x) = 6x3 + 7x2 - 10x + 9 and Q(x) = -2x3 + 4x - 5, then C(x) = 4x3 + 7x2 - 6x + 4.

• Multiply P with Q.For polynomial multiplication, if P(x) and Q(x) are polynomials of degree-bound n, we say that their product C(x) is a polynomialof degree-bound 2n - 1 such that C(x) = P(x) Q(x) forall x in the underlying field. You probably have multiplied polynomials before, by multiplyingeach term in P(x) by each term in Q(x) and combining termswith equal powers. For example,we can multiply P(x) = 6x3 + 7x2 - 10x + 9 and Q(x) = -2x3 + 4x -5 as follows:

Another way to express the product C(x) is

• Divide P by Q to get a quotient and residue polynomials.

polynomial long division is an algorithm for dividing apolynomial by another polynomial of the same or lower degree,a generalised version of the familiar arithmetic techniquecalled long division. It can be done easily by hand, becauseit separates an otherwise complex division problem into

smaller ones. Sometimes using a shorthand version calledsynthetic division is faster, with less writing and fewercalculations.

Polynomial long division is an algorithm that implements theEuclidean division of polynomials, which starting from twopolynomials A (the dividend) and B (the divisor) produces, if Bis not zero, a quotient Q and a remainder R such that

A = BQ + R,

and either R = 0 or the degree of R is lower than the degreeof B. These conditions define uniquely Q and R, which meansthat Q and R do not depend on the method used to computethem.

Example

Find the quotient and the remainder of the division ofthe dividend, by

the divisor.The dividend is first rewritten like this:

The quotient and remainder can then be determined as follows:1. Divide the first term of the dividend by the highest

term of the divisor (meaning the one with the highest power of x, which in this case is x). Place the result above the bar (x3 ÷ x = x2).

2. Multiply the divisor by the result just obtained (the first term of the eventual quotient). Write the resultunder the first two terms of the dividend (x2 · (x − 3) = x3 − 3x2).

3. Subtract the product just obtained from the appropriate terms of the original dividend (being careful that subtracting something having a minus sign is equivalent to adding something having a plus sign), and write the result underneath ((x3 − 2x2) − (x3 − 3x2) = −2x2 + 3x2 = x2) Then,"bring down" the next term from the dividend.

4. Repeat the previous three steps, except this time usethe two terms that have just been written as the

dividend.

5. Repeat step 4. This time, there is nothing to "pull down".

The polynomial above the bar is the quotient q(x), and the number left over ( 5) is the remainder r(x).

The long division algorithm for arithmetic is very similar to the above algorithm, in which the variable x is replaced by the specific number 10.

3. Consider a rooted binary tree T with the followingnode traversal orders: Pre-order: M E D C A B L K J GF I HIn-order: A C B D E M K F G J I H L

(a) Construct the binary tree T.

M

E LD

K

C J

A B G I

FH

b)Computer the node order for the post-order traversal of T from root. A B C D E F G H I J K L(c) Design an algorithm to construct a binary tree from its Pre-order /Post-order and In-order traversal

Preorder(node)if node == null then

returnvisit(node)preorder(node.left)preorder(node.right)

In-orderinorder(node)if node == null then

returninorder(node.left)visit(node)inorder(node.right)

iterativePreorder(node) parentStack = empty stackwhile (not parentStack.isEmpty() or node ≠

null)if (node ≠ null)

visit(node)if (node.right ≠ null)

parentStack.push(node.right)node = node.left

elsenode = parentStack.pop()

iterativeInorder(node) parentStack = empty stackwhile (not parentStack.isEmpty() or node ≠

null)if (node ≠ null)

parentStack.push(node) node = node.left

elsenode = parentStack.pop() visit(node)node = node.right

Post-orderpostorder(node) iterativePostorder(node)if node == null then parentStack = empty stack

return lastnodevisited = nullpostorder(node.left) while (not parentStack.isEmpty() or node ≠postorder(node.right) null)visit(node) if (node ≠ null)

parentStack.push(node)node = node.left

elsepeeknode = parentStack.peek()if (peeknode.right ≠ null and

lastnodevisited ≠ peeknode.right)/* if right child exists AND traversing

node from left child, move right */node = peeknode.right

elsevisit(peeknode)lastnodevisited = parentStack.pop()

d) Can a tree be constructed from its Pre-order and Post-order traversals? Present an algorithm or provide a counter example.

Inorder sequence: D B E A F CPreorder sequence: A B D E C F

In a Preorder sequence, leftmost element is the root of the tree. So we know ‘A’ is root for given sequences. By searching‘A’ in Inorder sequence, we can find out all elements on left side of ‘A’ are in left subtree and elements on right are in right subtree. So we know below structure now.

A/ \

/ \ D B E F C

We recursively follow above steps and get the following tree.

A/ \

/ \ B C/ \ /

/ \ /D E F

Algorithm: buildTree()1) Pick an element from Preorder. Increment a Preorder IndexVariable (preIndex in below code) to pick next element in nextrecursive call. 2) Create a new tree node tNode with the data as pickedelement.

3) Find the picked element’s index in Inorder. Let the indexbe inIndex.

4) Call buildTree for elements before inIndex and makethe built tree as left subtree of tNode. 5) Call buildTree for elements after inIndex and makethe built tree as right subtree of tNode. 6) return tNode.

4. Define suitable data structures for the following 2-Dgeometric objects and illustrate each with an example. Makesuitable assumptions for each data structure if you need. Stateyour assumptions clearly.(a) Point and Line Segment (b) Triangle and Rectangle

(c) Simple Polygon

Using one or more of the above data structures, briefly outlinean O(n) algorithm to compute the area of an n-vertex simplepolygon. Illustrate the working of your algorithm by computingthe area of the following EDCBA polygon.

Point:-

Many two-dimensional geometric shapes can bedefined by a set of points or vertices andlines connecting the points in a closed chain,as well as the resulting interior points. Suchshapes are called polygons and includetriangles, squares, and pentagons. Other shapesmay be bounded by curves such as the circle orthe ellipse.

Two-dimensional points

where c1 through cn and d are constants and n is the dimension of the space.

Line:-

A line segment is a part of a line that is boundedby two distinct end points and contains every pointon the line between its end points. Depending onhow the line segment is defined, either of the twoendpoints may or may not be part of the line segment. Two or more linesegments may have some of the same relationships as lines, such asbeing parallel, intersecting, or skew, but unlike lines they may benone of these.

Triangle:-

A triangle is a polygon with three edges and threevertices. It is one of the basic shapes in geometry. A

triangle with vertices A, B, and C is denoted . In Euclidean geometry any three points, when non-

collinear, determine a unique triangle and a uniqueplane (i.e. a two-dimensional Euclidean space).

Rectangles : Rectangles have been the most popular and common geometric form for buildings since the shape is easy to stack and organize; as a standard, it is easy to design furniture and fixtures to fit inside rectangularly shaped buildings.

Polygon:-

The basic geometrical notion has been adapted in various ways to suit particular purposes. Mathematicians are often concerned only with the bounding closed polygonal chain and with simple polygons which do not self-intersect, and they often define a polygon accordingly. A polygonal boundary may be allowed to intersect itself, creating star polygons. Geometrically two edges meeting at acorner are required to form an angle that is not straight (180°); otherwise, the line segments may be considered parts of a single edge; however mathematically, such corners may sometimes be allowed.

By selecting , the area formula of each triangle reduces to

. This yields:

A little algebra shows that the more efficient second and third summations are equal to the first. For a polygon with nvertices, the first summation uses 2n multiplications and (2n–1) additions; the second uses n multiplications and (3n–1) additions;and the third uses only n

multiplications and (2n–1) additions. So, the third is preferred for efficiency. And, to avoid any overhead from computing the index i(mod n), one can either extend the polygon arrayup to , or simply put the final term outside of the summation loop. We give an efficient implementation below in the routine.

This computation gives a signed area for a polygon; and, similar to the signed area of a triangle, is positive when thevertices are oriented counterclockwise around the polygon, and negative when oriented clockwise. So, this computation can be used to test for a polygon's global orientation. However, there are other more efficient algorithms for determining polygon orientation. The easiest is to find the rightmost lowest vertex of the polygon, and then test the orientation of the entering and leaving edges at this vertex. This test can be made by checking if the end vertex of the leaving edge is to the left of the entering edge, which means that the orientation is counterclockwise, otherwise it is clockwise.

Steps to compute the area of the EDCBA polygon

1 Make a table with

X Y

A 14.5

=3.5-18=-14.5

B 43.5 =25-24.5=.5

C 7 5=14-27.5=-13.5

D5.5 2 =5.5-4=1.5

AREA=|-13.5/2|=6.75

E 2 1 =9-1=8

A 14.5 Total=-13.5

the x,y coordinates of each vertex. Start at any vertex and go around the polygon in either direction. Add the starting vertex again at the end.2 Combine the first two rows by:

1. Multiplying the first row x by the second row y. 2. Multiplying the first row y by the second row x . 3. Subtract the second product form the first.

3 Repeat this for rows 2 and 3, then rows 3 and 4 and so on.

4 Add these results, make it positive if required, and divide b

Algorithm

"close" polygon x[N] = x[0]; x[N+1] = x[1];

y[N] = y[0]; y[N+1] = y[1];

// compute area area = 0;for( size_t i = 1; i <= N; ++i ) area +=x[i]*( y[i+1] - y[i-1] );area /= 2;

Algorithm :Steps to compute the area of theEDCBA polygon

self.tp1= 1,4.5,4,3.5,7,5,5.5,2,2,1,1,4.5 def area(self):

self.tox=0self.toy=0for i in range(0,len(self.tp1),2): if i+3 > len(self.tp1):self.tox +=

self.tp1[i]*self.tp1[1] else:self.tox += self.tp1[i]*self.tp1[i+3]

for i in range(1,len(self.tp1),2): if i+2 > len(self.tp1):self.toy +=

self.tp1[i]*self.tp1[0] else:print i,self.tp1[i]self.toy +=

self.tp1[i]*self.tp1[i+1] print abs(self.tox-self.toy)/2,"area"

5. Consider the vertex-edge-face arrangement below:

(a) Fill up the DCEL (Doubly Connected Edge List) data structure (as outlined in the video) in the table to represent it.

(b) Briefly explain how you can perform each of the followingoperations in a DCEL: • Walk around the boundary of a givenface in counterclockwise order • Access a face from anadjacent one • Visit all the edges around a given vertex

(c) Illustrate the working of each of the operations inProblem 5b for the DCEL you have constructed in Problem 5a.

a)

Half-

origin Twin edge

Incident Next Prev

Edge Edge Edge Edgee1,a v1 e1,a;e3,b e3,b e1,b e1,ae1,b v2 e1,b;e4,b e4,b e4,a e1,be2,a v3 e4,a;e3,a e3,a e3,b e4,ae2,b v4 e2,b e2,a e2,a e2,be3,a v3 e4,a;e3,a e3,a e4,b e4,ae3,b v1 e1,a;e3,b e3,b e1,b e1,ae4,a v2 e1,b;e4,b e4,b e1,a e1,be4,b v3 e4,a;e3,a e3,a e3,b e4,a

B. A DCEL is a set of faces, half-edges and vertices. Yes, anedge divided by two. A pair of half-edges forms an edge, andthey are called twins. So, each half-edge has a pointer toits twin half-edge, in order to reconstruct the whole edge.divide an edge by two because Each half edge is associated to oneface on one side of the edge, and one vertex on one end ofthe edge. In other words, a half-edge has a face pointer andan origin pointer. And the “doubly-connected” thing are Each half-edge has a next pointer and a previous pointer. The contour ofa face is defined by a sequence of half-edges linked by theirnext and previous pointers. Finally, a face has the boundarypointer which points to one half-edge on its contour. And thevertex has an incident pointer that points to one half-edgethat starts on that vertex.

C. Edge connected to everything in a very organized way. Fromone face, you can walk through his contour by following the

next (or previous) pointers of its boundary. From one half-edge, you can access one vertex through the origin pointerand the other vertex following its twin->origin pointers. Inthe same way, from a half-edge you can access the face onwhich it is part of the contour (by its face pointer), andthe other face by its twin half-edge (twin->face pointer). theedges that start on a given vertex is by Picking the vertex. The firsthalf-edge is in its incident pointer. Call it current. Forthe next half-edge, pick the previous->twin half-edge of thecurrent half-edge (and call this new one the new current).Keep getting these previous->twin pointers until you reachthe first half-edge, and the neighbouring faces

6. Consider a balanced binary search tree T holding nnumbers. You are given two numbers L and H. You need to sumup all the numbers in T that lie between L and H. Also,suppose there are m such numbers in T. Determine the tightestupper bound on the time to compute the sum

Explanation:-It takes (log n ) time to determine numbers n1 and n2 inbalanced binary search tree T such that1. n1 is the smallest number greater than or equal to L andthere is no predecessor n’1 of n1 such that n’1is equal ton1. 2. n2 is the largest number less than or equal to H andthere is no successor of n’2 of n2 such that is equal to n2.

Since there are m elements between n1 and n2, it takes ‘m’time to add all elements between n1 and n2.So time complexity is O (log n + m)

Searching and Sorting

7. The convex hull CH(S) of a set of n points S in 2D is thesmallest convex polygon containing the points S. Show thatfinding the convex-hull of n points is bounded by Ω(nlogn)steps.

Explanation:-

If we create the convex-hull in o(nlogn) time, this wouldimply, that We can sort n numbers in o(nlogn) time.

We do this with contradiction. We have n numbers (x1,x2,…,xn),which We would like to sort. From these numbers, We createpoints P in 2D space in some fashion. For example pi=(xi,x2i).

On these newly constructed points P We call the algorithm forconvex hull, which returns us the actual convex hull.

After that, We simultaneously traverse upper and lower hull,from the lower left-most point in which We find in O(n) time,

to the upper right-most point. With this traversal Weactually sort the numbers. Let pi and pj be the next points onlower and upper hull, then if xi<xj, We move one step ahead onthe lower hull and add xi to the end of the sorted array (elseWe take one step ahead on the upper hull and add xj to thearray). We then finish when the traversals meet in the upperright-most point of the convex hull.

The algorithm that we described is run in O(n) time. So ifthe convex-hull algorithm would be o(nlogn), the sorting of nnumbers could be also done in o(nlogn) time, which is acontradiction since we know that sorting n numbers takes atleast Ω(nlogn) time.

Hull(P, h) :(1) Let r ← n/h . (2) Partition P into disjoint subsets P1, P2, . . . , Pr

, each of size at most h. (3) For (i ← 1 to r)

compute Hull(Pi) using Graham's scan and store the vertices in an ordered array.

(4) Let p0 ← (−∞, 0) and let p1 be the bottommost pointof P .

(5) For (k ← 1 to h) (a) For (i ← 1 to r)

compute point tangent qi ∈ Hull(Pi), that is, the vertex of Hull(Pi) that maximizes the angle ∠pk−1pk qi.

(b) Let pk+1 be the point q ∈ q1, . . . , qr that maximizes the angle ∠pk−1pk q.

(c) If pk+1 ← p1 then return hp1, . . . , pk i (success). (6) (Unable to complete the hull after h iterations.) Return “Failure: h∗ is too small.”

The upshots of this are: (1) the Jarvis phase never performs for more than h stages, and(2) if h ≤ h, the algorithm succeeds in finding the hull.To analyze its runnin g time, recall that each partitionhas roughly h points, and so there are roughly n/h mini-hulls. Each tangent computation takes O(log h) time, andso each stage takes a total of O((n/h) log h) time. By (1)the number of Jarvis stages is at most h, so the totalrunning time of the Jarvis phase is O(h(n/h) log h) = O(nlog h).Combining this with the fact that the Graham phase takes O(nlog h) time, the total time of the restricted algorithm isO(n log h). If we maintain the condition that h≤ h2 then,irrespective of success or failure, the running time will beO(n log h).

Lower Bound (Optional): Next we will show that Chan'sresult is asymptotically optimal in the sense that anyalgo-rithm for computing the convex hull of n points withh points on the hull requires Ω(n log h) time. The proofis a generalization of the proof that sorting a set of nnumbers requires Ω(n log n) comparisons.If you recall the proof that sorting takes at least Ω(nlog n) comparisons, it is based on the idea that anysorting algorithm can be described in terms of a decisiontree. Each comparison has at most 3 outcomes (<, =, or >).Each such comparison corresponds to an internal node inthe tree. The execution of an algorithm can be viewed as atraversal along a path in the resulting 3-ary tree. Theheight of the tree is a lower bound on the worst-caserunning time of the algorithm. There are at least n!different possible inputs, each of which must be reordered

Convex Hull by Divide-and-Conquer: As with sorting, thereare many different approaches to solving the convex hullproblem for a planar point set P . Next we will consideranother O(n log n) algorithm, which is based on thedivide-and-conquer design technique. It can be viewed asa generalization of the famous MergeSort sortingalgorithm (see any standard algorithms text). Here is anoutline of the algorithm. It begins by sorting thepoints by their x-coordinate, in O(n log n) time. Theremainder of the algorithm is shown in the code sectionbelow.

Hull(P ) :(1) h ← 2. L ← fail. (2) while (L 6= fail)

(a) Let h ← min((h∗)2, n). (b) L ← RestrictedHull(P, h∗).

(3) Return L.

8. Find the maximum slope (largest absolute value of gradient) for a line connecting two points from a set of n points S in 2D in O(nlogn) time.

Slope Statistics: Today, we consider a simple warm-up exercise as an example of a typical problem in computationalgeometry. To motivate the problem, imagine that a medical experiment is run, where the therapeutic benefits of a certain treatment regimen is being studied. A set of n points in real 2-dimensional space, R2, is given. We denote this set by P = p1, . . . , pn, where pi = (ai, bi), where ai indicates the amount of treatment and bi indicates the therapeutic benefit. The hypothesis is that in creasing the amount of treatment by a units results in an increase in therapeutic benefit of b = s(Δa), where s is an unknown scale factor.

In order to study the properties of s, a statisticianconsiders the set of slopes of the lines joining pairs ofa points (since each slope represents the increase inbenefit f or a unit increase in the amount of treatment).For 1 ≤ i < j ≤ n,

So that we don't need to worry about infinite s lopes, let us make the simplifying assumption that

the a-coordinates of the points are pairwise distinct, andto avoid ties, let us assumethat the slopes are distinct. Let S = si,j | 1 ≤ i < j ≤ n. Clearly |S| = n2_ = n(n − 1)/2 = O(n2). Although the set S of slopes is of quadratic size, it is defined by a set of npoints. Thus, a natural question is whether we can answer statisticalquestions about the set S in time O(n) or perhaps O(n log n), rather than O(n2).

minimum maximumslope slope

pjpi bj −

biaj − ai s

=bj−bi

8th smallestslope

i,j aj−ai

(a) (b)

The slope si,j and the slope set S = si,j | 1 ≤ i < j n.

Counting Negative Slopes and Inversions: counting the number ofslopes that lie within a given interval [s−, s+]. Beforeconsidering the general problem, let us consider a simplerversion by considering the case where s− = 0 and s+ = +∞. Inother words, we will count the number of pairs (i, j) wheresi,j is nonnegative. This problem is interestingstatistically, because it represents the number of instancesin which increasing the amount of treatment results in anincrease in the therapeutic benefit.Our approach will be to count the number of pairs such that si,j is strictly negative. There is no loss of generality in doing this, since we can simply subtract the count from n2_ toobtain

the number of nonnegative slopes. (The reason for this otherformulation is that it will allow us to introduce the concept ofinversion counting, which will be useful for the generalproblem.) It will simplify the presentation to make theassumption that the sets of a-coordinates and b-coordinates aredistinct.Suppose we begin by sorting the points of P in increasing orderby their a-coordinates. Let P = hp1, . . . , pni be the resultingordered sequence, and let B = hb1 , . . . , bni be the associatedsequence of b -coordinates. Observe that, for 1 ≤ i < j ≤ n, bi >bj if and only if s i,j is negative. For 1 ≤ i < j ≤ n, we saythat the pair (i, j) is an inversion for B if bi > bj . Clearly,our task reduces to counting the number of inversions of B

3 negative slopes

6 inducesinversion

b2

i 3s

b4

j

3 inversions BL: 2 4 6 8 BR:

0 1 59

b1

b3a1 a2 a3 a4 M : 0 1 2 4 5 6

(a)(b)

Inversion Counting: Counting the number of inversions in a sequence of n numbers is a simple exercise, which can be solvedin O(n log n) time.

InvCount(B) [Input: a sequence B; Output: sorted sequence M and inversion count I.]

(1) Partition B into disjoint subsets BL and BR, each ofsize at most n/2 , where n = |B|;

(2) (BL, IL) ←InvCount(BL);(BR, IR) ←InvCount(BR);

(3) Let i ← j ← 1; I ← 0; M ← ; (4) While (i ≤ |BL| and j ≤ |BR|)

(a) if (BL[i] ≤ BR[j]) append BL[i++] to M and I ← I + (j −

1); (b) else append BR[j++] to M ; On exitting the loop, either i > |BL| or j > |BR|.

(5) If i ≤ |BL|, append BL[i . . . ] to M and I ← I + (|BL|− i + 1)|BR|;

(6) Else (we have j ≤ |BR|), append BR[j . . . ] to M ; (7) return (M, IL + IR + I);

The running time exactly matches tha. It obeys the well known recurrence T (n) = 2T (n/2) + n, which solves to O(n log n).By combining this with the above reduction from slope range counting over negative slopes, we obtain an O(n log n) time algorithm for counting nonnegative slopes.cular, if i ≤ |BL|,we append the remaining |BL| − i + 1 elements of BL to M . Since these elements are all larger than any element of BR, we add (|BL| − i + 1)|BR| to the inversion counter. (When copying the remaining elements from BR, there is no need to modify the inversion counter.) See the code block below for the complete code.

InvCount(B) [Input: a sequence B; Output: sorted sequence M and inversion count I.]

(5) Partition B into disjoint subsets BL and BR, each ofsize at most n/2 , where n = |B|;

(6) (BL, IL) ←InvCount(BL);(BR, IR) ←InvCount(BR);

(7) Let i ← j ← 1; I ← 0; M ← ; (8) While (i ≤ |BL| and j ≤ |BR|)

(a) if (BL[i] ≤ BR[j]) append BL[i++] to M and I ← I + (j −1);

(b) else append BR[j++] to M ; On exitting the loop, either i > |BL| or j > |BR|.

(8) If i ≤ |BL|, append BL[i . . . ] to M and I ← I + (|BL|

− i + 1)|BR|; (9) Else (we have j ≤ |BR|), append BR[j . . . ] to M ; (10) return (M, IL + IR + I);

The running time exactly matches that of MergeSort. It obeys the well known recurrence T

(n) = 2T (n/2) + n, which solves to O(n log n).By combining this with the above reduction from slope range counting over negative slopes, we obtain an O(n log n) time algorithm for counting nonnegative slopes.

pj∗ : y = ajx − bj

bj−bi ysi,j = aj−ai pi∗ : y = aix − bi

bj pjbi pi

xai aj bj−bi

si,j = aj−ai(A) (B)

Point-line duality and the relationship between the slope of a line between two points and the x-coordinate of the duals of the two points.

Letting Y = hy1, . . . , yni denote the resulting sequence, itis easy to see that the number of inversions in −Y is equalto the number of pairs of lines that intersect within theslab. The time to compute the intersection along the leftside and sort according to this order is O(n log n), and thetime to compute the intersections with the right side andcount the inversions is also O(n log n). Therefore, the totalrunning time is O(n log n).

9. Design an algorithm that finds if there exist two elements in a given array A of n numbers that add up to a given value x.ArrayhasTwocandidates(A[], ar_size, sum)

1) Sort the array in non-decreasing order. 2) Initialize two index variablesto find the candidate elements inthe sorted array. (a) Initialize first to the leftmost index: l = 0 (b) Initialize second the rightmost index: r = ar_size-1

3) Loop while l < r. (a) If (A[l] + A[r] == sum) then return 1 (b) Else if( A[l] + A[r] < sum ) then l++ (c) Else r--

4) No candidates in whole array THEN return 0

EXAMPLE:Let Array be 1, 4, 45, 6, 10, -8 and sum to find be 16

Sort the arrayA = -8, 1, 4, 6, 10, 45

Initialize l = 0, r = 5

A[l] + A[r] ( -8 + 45) > 16 => decrement r. Now r = 10A[l] + A[r] ( -8 + 10) < 2 => increment l. Now l = 1A[l] + A[r] ( 1 + 10) < 16 => increment l. Now l = 2A[l] + A[r] ( 4 + 10) < 14 => increment l. Now l = 3A[l] + A[r] ( 6 + 10) == 16 => Found candidates (return 1)

10. You are given an array that is almost sorted whereeach of the N elements may be misplaced by no more thank positions from the correct sorted order. Find aspace-and-time efficient algorithm to sort the array.Let's denote arr[0..n) to mean the elements of the array from index 0 (inclusive) to N (exclusive).

Sort arr[0..2k)Now we know that arr[0..k) are in their final sorted positions......but arr[k..2k) may still be misplaced by k! Sort arr[k..3k)Now we know that arr[k..2k) are in their final sorted positions...

...but arr[2k..3k) may still be misplaced by k Sort arr[2k..4k)....Until you sort arr[ik..N), then it is finished!This final step may be cheaper than the other steps when you haveless than 2k elements leftIn each step, you sort at most 2k elements in O(k log k), puttingat least k elements in their final sorted positions at the end ofeach step. There are O(N/k) steps, so the overall complexity isO(N log k).