Académique Documents
Professionnel Documents
Culture Documents
Uzma Rifat
05/04/2015
Divide and Conquer
Big problem
Difficult to solve
Divide: Divide the problem into smaller
problems
Conquer: Solve the smaller problems
Combine: Combine the solution
Methods
Substitution Method
Recursion Tree
Master Theorem
Merge Sort
If the number of items 0 or 1 return
Otherwise divide it into two or three subparts
Recursively sort the sub-parts
Merge the sorted parts into one
Pseudocode
MergeSort (Array(First..Last))
Begin
If Array contains only one element Then
Return Array
Else
Middle= ((Last + First)/2)
LeftHalfArray = MergeSort(Array(First..Middle))
RightHalfArray = MergeSort(Array(Middle+1..Last))
ResultArray = Merge(LeftHalfArray, RightHalfArray)
Return ResultArray
EndIf
End MergeSort
package com.java2novice.sorting;
}
}
Cost Analysis
D (n) Cost of Dividing O (1)
C (n) Cost of Combining O (n)
T (n)= { O (1) T (n/2)
aT(n/b)+ D(n)+C(n) otherwise
Quick Sort
Best practical choice for sorting
Complexity O(n log n)
Worst case complexity O(n2)
Works on divide and conquer approach
Chooses pivot
Works around pivot element
Algorithm
Pick an element, called a pivot, from the array.
Reorder the array so that all elements with values
less than the pivot come before the pivot, while
all elements with values greater than the pivot
come after it (equal values can go either way).
After this partitioning, the pivot is in its final
position. This is called the partition operation.
Recursively apply the above steps to the sub-
array of elements with smaller values and
separately to the sub-array of elements with
greater values.
int partition(int arr[], int left, int right)
{
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
return i;
}
void quickSort(int arr[], int left, int right) {
int index = partition(arr, left, right);
if (left < index - 1)
quickSort(arr, left, index - 1);
if (index < right)
quickSort(arr, index, right);
}