Vous êtes sur la page 1sur 11

Design & Analysis of Algorithms

Submitted To
Prof. Hashim Javed
Submitted By
Affifa
ID: 30
21-Aug-2019
Quick sort
Quick sort is one of the most famous sorting
algorithms based on divide and conquers
strategy which results in an O(n log n)
complexity. So, the algorithm starts by picking
a single item which is called pivot and moving
all smaller items before it, while all greater
elements in the later portion of the list.
• This is the main quick sort operation named as
a partition, recursively repeated on lesser and
greater sub-lists until their size is one or zero -
in which case the list is wholly sorted.
Choosing an appropriate pivot, as an example,
the central element is essential for avoiding
the severely reduced performance of O(n2).
There are many different versions of quick Sort
that pick pivot in different ways.
• Always pick first element as pivot.
• Always pick last element as pivot
(implemented below)
• Pick a random element as pivot.
• Pick median as pivot.
• The key process in quick Sort is partition().
Target of partitions is, given an array and an
element x of array as pivot, put x at its correct
position in sorted array and put all smaller
elements (smaller than x) before x, and put all
greater elements (greater than x) after x. All
this should be done in linear time.
Pseudo Code for recursive QuickSort
function :
• /* low --> Starting index, high --> Ending index */
quickSort(arr[], low, high)
• {
• if (low < high)
• {
• /* pi is partitioning index, arr[pi] is now at right place */
• pi = partition(arr, low, high);
• quickSort(arr, low, pi - 1); // Before pi quickSort(arr, pi +
1, high); // After pi } }
Merge Sort Algorithm

• This algorithm is based on splitting a list, into


two comparable sized lists, i.e., left and right
and then sorting each list and then
merging the two sorted lists back together as
one. Merge sort can be done in two types
both having similar logic and way of
implementation.
• Merge sort can be done in two types both
having similar logic and way of
implementation. These are:
• Top down implementation
• Bottom up implementation
Below given figure shows how Merge Sort
works:
See following C implementation for details.

• MergeSort(arr[], l, r)
• If r > l
• 1. Find the middle point to divide the array into two halves:
• middle m = (l+r)/2
• 2. Call mergeSort for first half:
• Call mergeSort(arr, l, m)
• 3. Call mergeSort for second half:
• Call mergeSort(arr, m+1, r)
• 4. Merge the two halves sorted in step 2 and 3:
• Call merge(arr, l, m, r)

Vous aimerez peut-être aussi