Divide & conqre

Post on 25-May-2015

47 views 1 download

Tags:

Transcript of Divide & conqre

Divide &

conquer

DIVIDE AND CONQUER RULEDEFINITION:

The divide-and-conquer rule consists in breaking a problem into simpler sub-problems of the same type, next to solve these sub-problems, finally to merge the obtained results into a solution to the problem.

Why we use it?

Divide and conquer technique is used for sorting the elements of array in some specific order.

ALGORITHM:Dividing the main problem into smaller ones.These smaller sub-problems are divided further.Recombine them to achieve the main objective.

ANALYSIS:Let’ see few analysis to confirm the usefulness of the divide and conquer technique.To sort the one major problem time is nlog(n)2To sort the halves approximate time is (n/2) 2+(n/2) 2To merge the two halves approximate time is n

So, for n=100, divide and conquer takes approximately:= (100/2) 2 + (100/2) 2 + 100= 2500 + 2500 + 100= 5100

Suppose that n is 100. Considering if we apply insertion sort algorithm on it then thetime taken will be approximately (100) 2 n = 10000. Now, if we apply divide and conquer technique on it. Then for first half approximate time will be (100/2) 2. Similarly for second half it will be (100/2) 2. The merging approximate time will be 100. So the whole operation of sorting using this divide and conquer technique in insertion sort will take around (100/2) 2 + (100/2)2+100 = 5100. Clearly the time spent (5100) after applying divide and conquer mechanism is significantly lesser thanthe previous time (10000).

WORKING:

subproblem 2 of size n/2

subproblem 1 of size n/2

a solution to subproblem 1

a solution tothe original problem

a solution to subproblem 2

a problem of size n

EXAMPLES:

Merge sortQuick sort

EXAMPLE OF MERGE SORT

5 10 3 8

Suppose we have an array of four elements

5 10 3 8

5 10 3 8

5 10 3 8

5 10 3 8

5 10 3 8

5 10

3

8

5 10 3 8

5 10

3

8

5 10 3 8

5

10

3

8

5 10 3 8

5

10

3

8

5 10 3 8

5

10

3 8

5 10 3 8

5 103 8

Un sorted

sorted

EXAMPLE OF QUICK SORT

5 10 3 8

Suppose we have an array of five elements

1

5 10 3 8 1

pivot

5 10 3 8 1

5 10 3 8 1

5

10 3 8

1

510 3 81

510 3 81

5

10

3 81

5

10

3 81

5103 81

5 103 81

pivot

5 103 81

5 103 81

5

10

3 81

5

10

3 81

5 103 81

5 103 81

sorted