SlideShare a Scribd company logo
1302251 Data Structures and Algorithms




                    Lecture 11
                     Sorting
                    Aj. Khwunta Kirimasthong
                 School of Information Technology
                    Mae Fah Luang University
Outline

   Sorting Concept
   Sorting Algorithm
       Selection Sort
       Insertion Sort
       Merge Sort
       Quick Sort




                         2
Sorting Concept

   Sorting is the operation of arranging data in some
    given order, such as
       Ascending
           the dictionary, the telephone book
       Descending
           grade-point average for honor students
   The sorted data can be numerical data or character
    data.
   Sorting is one of the most common data-processing
    applications.

                                                         3
Sorting Concept (Cont.)

   Sorting problem
    Let A be a sequence of n elements. Sorting A refers
    to the operation of rearranging the content of A so
    that they are increasing in order.
    Input: A: the sequence of n numbers ( a1 , a 2 , ..., a n )
    Output: A: the reordering ( a1 , a 2 ,..., a n ) of the
    input sequence such that
                     a1   a2         an


                                                             4
Selection Sort
   One of basic sorting algorithms
   Selection Sort works as follows:
       First, find the smallest elements in the data
        sequence and exchange it with the element in the
        first position,
       Then, find the second smallest element and
        exchange it with the element in the second
        position and
       Continue in this way until the entire sequence is
        sorted.

                                                            5
Selection Sort Example
    1   2   3   4   5   6             1   2   3   4   5   6
A   5   2   4   6   1   3   (1)   A   1   2   4   6   5   3

                                      1   2   3   4   5   6
                            (2)   A   1   2   4   6   5   3

                                      1   2   3   4   5   6
                            (3)   A   1   2   3   6   5   4

                                      1   2   3   4   5   6
                            (4)   A   1   2   3   4   5   6

                                      1   2   3   4   5   6
                            (5)   A   1   2   3   4   5   6

                                      1   2   3   4   5   6
                            (6)   A   1   2   3   4   5   6

                                                              6
Selection Sort Algorithm

Algorithm SelectionSort(A,n)
Input: A: a sequence of n elements
       n: the size of A
Output: A: a sorted sequence in ascending order
      for i = 1 to n
           min = i
           for j = i+1 to n
                if A[j] < A[min] then
                     min = j
           Swap(A,min,i)

                                                  7
Selection Sort Algorithm (Cont.)
Algorithm: Swap(A,min,i)
Input: A : a sequence of n elements
      min: the position of the minimum value of A
  while considers at index i of A
      i: the considered index of A
Output: exchange A[i] and A[min]
           temp = a[min]
           a[min] = a[i]
           a[i] = temp


                                                    8
Selection Sort Analysis

   For i = 1, there are _(n-1)_ comparisons to find the
    first smallest element.
   For i = 2, there are _(n-2)_ comparisons to find the
    second smallest element, and so on.
   Accordingly,                            n   1

         (n-1) + (n-2) + (n-3) + … + 2 + 1 =   i = n(n-1)/2
                                            i   1




   The best case running time is ___ (n2)__
   The worst case running time is __ O(n2)__


                                                          9
Insertion Sort

   To solve the sorting problem
   Insertion sort algorithm is almost as simple as
    selection sort but perhaps more flexible.
   Insertion sort is the method people often
    use for sorting a hand of cards.




                                                  10
Insertion Sort (Cont.)

   Insertion sort uses an incremental approach:
    having the sorted subarray A[1…j-1], we
    insert the single element A[ j ] into its proper
    place and then we will get the sorted
    subarray A[ 1…j ]
                       pick up




        Sorted order             Unsorted order

                                                   11
Insertion Sort Example
           1       2       3       4       5       6

           5       2       4       6       1       3
                   key = A[j]
               1    2     3            4       5   6

    (1)   A 5          2       4   6       1       3   key     2



               1       2       3       4       5   6

    (2)   A 2          5       4   6       1       3   key     4



               1       2       3       4       5   6

    (3)   A 2          4       5   6       1       3   key     6


                                                             in-place sorted
                                                                           12
Insertion Sort Example (Cont.)
             1   2   3   4   5   6
     (4)   A 2   4   5   6   1   3   key   1




             1   2   3   4   5   6
     (5)   A 1   2   4   5   6   3   key   3




            1    2   3   4   5   6
     (6)   A 1   2   3   4   5   6

                                       in-place sorted

                                                    13
Insertion Sort Algorithm

Algorithm: INSERTION-SORT(A)
Input: A : A sequence of n numbers
Output: A : A sorted sequence in increasing order of array A
  for j = 2 to length(A)
      key = A[j]
      //Insert A[j] into the sorted sequence A[1…j-1]
      i = j-1
      while i > 0 and A[i] > key
            A[i+1] = A[i]
            i = i-1

      A[i+1] = key


                                                          14
Insertion Sort Analysis

   The running – time of INSERTION-SORT
    depends on the size of input.




                                           15
Insertion Sort Analysis (cont.)
 INSERTION-SORT(A)                                      cost       times
 1. for j = 2 to length(A)                                c1                   n

 2.   key = A[j]                                          c2                   n-1

 3.   //Insert A[j] into the sorted sequence A[1…j-1]     0                    n-1

 4.   i = j-1                                             c4                   n-1
                                                                               n

 5.   while i > 0 and A[i] > key                          c5                           tj
                                                                           j       2
                                                                   n
 6.        A[i+1] = A[i]                                  c6               (t j         1)
                                                               j       2
                                                                   n
 7.        i = i-1                                        c7               (t j         1)
                                                               j       2

 8.   A[i+1] = key                                        c8                   n-1

                                                                                        16
Analysis of Insertion Sort (Cont.)

   To Compute the total running time of INSERTION-
    SORT, T ( n )

                                                                                   n
       T (n)   c1 n    c2 (n        1)   0(n       1)       c4 (n    1)      c5         tj
                                                                                  j 2

                       n                       n
                  c6         (t j   1)   c7          (t j    1)     c8 ( n    1)
                       j 2                     j 2




                                                                                             17
Analysis of Insertion Sort (Cont.)

   Best – case
       If input array is already sorted. Thus tj = 1



    T(n) = c1n+c2(n-1)+(0)(n-1)+c4(n-1)+c5(n-1)+c6(0)+c7(0)+c8(n-1)
        = (c1+c2+c3+c4+c5+c8)n - (c2+c3+c4+c5+c8)

                                                        an + b for constant a and b



Base-case running time of INSERTION-SORT is                            (n)

                                                                              18
Analysis of Insertion Sort (Cont.)
   Worse – case
       If input array is in reverse sorted order. Thus tj = j
                                                                                       n(n    1)
               T (n)   c1 n    c2 (n         1)           c4 (n      1)         c5                     1
                                                                                          2
                                    (n       1) n                    (n        1) n
                              c6                            c7                           c8 ( n    1)
                                         2                                 2
                       c5      c6        c6           2                                  c5       c6       c7
               T (n)                              n             c1        c2      c4                            c8 n
                        2      2   2                                                     2         2       2
                               (c2 c4                      c5        c8 )               an
                                                                                              2
                                                                                                       bn       c
                                                                                       for constant a, b and c

                                                                                                                    2
 Worse-case running time of INSERTION-SORT is                                                                   (n )

                                                                                                                    19
Analysis of Insertion Sort (Cont.)

   Worse – case (Cont.)
        If input array is in reverse sorted order. Thus tj = j
                                                                                    n
         n            n                                                                        n(n     1)
                                     n(n       1)                                         j
              tj           j                        1                               j 1
                                                                                                   2
        j 2          j 2                  2


        n                      n
                                                    (n   1)(( n   1)   1)                 (n    1) n
              (t j   1)              (j       1)                            (1 1)
        j 2                    j 2                           2                                 2




                                                                                                            20
Divide and Conquer
     Approach

Merge Sort
Quick Sort
Divide-and-Conquer Approach

   The divide-and-conquer approach involves
    three steps at each level of the recursion:
       Divide the problem into a number of sub-problems
        that are similar to the original problem but smaller
        in size.
       Conquer the sub-problems by solving them
        recursively.
       Combine the solution of subproblems into the
        solution for the original problem.


                                                           22
Merge Sort

   The Merge Sort algorithm closely follows the
    divide-and-conquer approach. It operates as
    follows,
       Divide: Divide the n-element sequence to be
        sorted into two subsequences of n/2 elements
        each.
       Conquer: Sort the two subsequences recursively
        using merge sort
       Combine: Merge the two sorted subsequences to
        produce the sorted solution.
                                                     23
Merge Sort (Cont.)

   The recursion “bottom out” when the
    sequence to be sorted has length 1, in which
    case there is no work to be done, since every
    sequence of length 1 is already in sorted
    order.




                                                24
Merge Sort Example                                                                  DIVIDE
                                                                                    &
                        0       1   2   3       4       5                           CONQUER
                A       5       2   4   6       1       3

            0   1   2                                           3       4   5
            5   2   4                                           6       1   3

    0   1                   2                       3       4                   5
    5   2                   4                       6       1                   3

0           1                               3                       4
5           2                               6                       1




                                                                                        25
Merge Sort Example (cont.)
                        0       1   2   3       4       5
                                                                                    COMBINE
                A       1       2   3   4       5       6

            0   1   2                                           3       4   5
            2   4   5                                           1       3   6

    0   1                   2                       3       4                   5
    2   5                   4                       1       6                   3

0           1                               3                       4
5           2                               6                       1




                                                                                        26
Merge Sort Algorithm

Algorithm MergeSort( A, p, q )
Input: A: a sequence of n elements
      p: the beginning index of A
      q: the last index of A
Output: A: a sorted sequence of n elements
     if(p < q) then
            r = floor((p+q)/2)
            MergeSort(A,p,r)
            MergeSort(A,r+1,q)
            Merge(A,p,r,q)

                                             27
Algo Merge(A,p,r,q)
Input: A, p, r, q : a sorted subsequences A[p…r] and
                    A[r+1…q]
Output: A: a sorted sequence A[p…q]

            let i=p, k=p, j=r+1
            while (i ≤ r) and (j ≤ q)
                   if (A[i] ≤ A[j]) then
                       B[k] = A[i]
                        k++
                        i++
                    else
                        B[k] = A[j]
                        k=k+1
                        j=j+1
            if (i>r) then /* If the maximum value of left subsequence is less than the right subsequence */
                    while(j ≤ q)
                        B[k] = A[j]
                        k++
                        j++
            else if(j > q) then /* If the maximum value of left subsequence is gather than the right subsequence */
                    while(i ≤ r)
                        B[k] = A[i]
                        k++
                        i++
            for k = p to q
                    A[k] = b[k]
                                                                                                           28
Merge Sort Analysis

   The best case running time is _ (n log n)_
   The worst case running time is _ O(n log n) _




                                                29
Quick Sort

   Quick Sort, likes merge sort, is based on the
    divide-and-conquer approach.
   To sort an array A[p…r]
       Divide: Partition (rearrange) the array A[p…r] into
        two subarray A[p…q -1] and subarray A[q+1…r]
        such that:
           Each element of A[p…q -1] is less than or equal to A[q]
           Each element of A[q+1…r] is greater than A[q]




                                                                      30
Quick Sort (Cont.)

   To sort sorting an array A[p…r] (cont.)
       Conquer: Sort the two subarray A[p…q -1] and
        A[q+1…r] by recursive calls to QuickSort.
       Combine: Since the subarrays are sorted in place, no
        work is needed to combine them: the entire array
        A[p…r] is now sorted.




                                                           31
Quick Sort Example
            0   1   2   3   4   5
        A   5   2   4   6   1   3




                                    32
Quick Sort Algorithm
Algo QuickSort(A, p, r)
   Input: A: A sequence of n numbers
            p: The first index of A
            r: The last index of A
    Output: A: A sorted sequence in increasing order of array A
                                      • Rearrange the subarray
    if (p < r) then                   A[p…r] in place.
                                      • The elements that is less
       q = Partition(A,p,r)           than A[q] are placed at the
                                      left side of A[q] and
       QuickSort(A,p,q-1)             • The elements that is
                                      greater than A[q] are placed
       QuickSort(A,q+1,r)             at the right side of A[q].


                                                                33
Quick Sort Algorithm (Cont.)
Algo Partition(A, p, r)
    Input: A: A sequence of n numbers
               p: The first index of A
               r: The last index of A
      Output: A: The rearranged subarray A[p…r]
        key = A[r]
        i=p–1
        for j = p to r -1
               if A[ j ] ≤ key then
                         i = i+1
                         exchange A[i] and A[j]
        exchange A[i+1] and key
        return i+1                                34
Quick Sort Analysis

   The best case running time is _ (n log n)_
   The worst case running time is _ O(n2)_




                                                 35
Q&A

More Related Content

What's hot

Sorting ppt
Sorting pptSorting ppt
Sorting ppt
Hassan Mustafa
 
Sorting.ppt read only
Sorting.ppt read onlySorting.ppt read only
Sorting.ppt read only
VARSHAKUMARI49
 
Sorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderSorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha Majumder
Ashin Guha Majumder
 
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
Lecture 3  data structures & algorithms - sorting techniques - http://techiem...Lecture 3  data structures & algorithms - sorting techniques - http://techiem...
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
Dharmendra Prasad
 
Sorting
SortingSorting
Sorting
Gopi Saiteja
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
Maher Alshammari
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
Rahul Jamwal
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
Trupti Agrawal
 
Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)
Hossain Md Shakhawat
 
Merge sort
Merge sortMerge sort
Merge sort
Rojin Khadka
 
Hub 102 - Lesson 5 - Algorithm: Sorting & Searching
Hub 102 - Lesson 5 - Algorithm: Sorting & SearchingHub 102 - Lesson 5 - Algorithm: Sorting & Searching
Hub 102 - Lesson 5 - Algorithm: Sorting & Searching
Tiểu Hổ
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
Dorina Isaj
 
Mergesort
MergesortMergesort
Mergesort
luzenith_g
 
Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Algorithm & data structures lec4&5
Algorithm & data structures lec4&5
Abdul Khan
 
3.5 merge sort
3.5 merge sort3.5 merge sort
3.5 merge sort
Krish_ver2
 
3.8 quick sort
3.8 quick sort3.8 quick sort
3.8 quick sort
Krish_ver2
 
Chapter 14 Searching and Sorting
Chapter 14 Searching and SortingChapter 14 Searching and Sorting
Chapter 14 Searching and Sorting
MuhammadBakri13
 
Data Structures- Part4 basic sorting algorithms
Data Structures- Part4 basic sorting algorithmsData Structures- Part4 basic sorting algorithms
Data Structures- Part4 basic sorting algorithms
Abdullah Al-hazmy
 
Quick and radix sort
Quick and radix sortQuick and radix sort
Quick and radix sort
Aaron Joaquin
 
Presentation
PresentationPresentation
Presentation
Sayed Hoque
 

What's hot (20)

Sorting ppt
Sorting pptSorting ppt
Sorting ppt
 
Sorting.ppt read only
Sorting.ppt read onlySorting.ppt read only
Sorting.ppt read only
 
Sorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderSorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha Majumder
 
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
Lecture 3  data structures & algorithms - sorting techniques - http://techiem...Lecture 3  data structures & algorithms - sorting techniques - http://techiem...
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
 
Sorting
SortingSorting
Sorting
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)
 
Merge sort
Merge sortMerge sort
Merge sort
 
Hub 102 - Lesson 5 - Algorithm: Sorting & Searching
Hub 102 - Lesson 5 - Algorithm: Sorting & SearchingHub 102 - Lesson 5 - Algorithm: Sorting & Searching
Hub 102 - Lesson 5 - Algorithm: Sorting & Searching
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Mergesort
MergesortMergesort
Mergesort
 
Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Algorithm & data structures lec4&5
Algorithm & data structures lec4&5
 
3.5 merge sort
3.5 merge sort3.5 merge sort
3.5 merge sort
 
3.8 quick sort
3.8 quick sort3.8 quick sort
3.8 quick sort
 
Chapter 14 Searching and Sorting
Chapter 14 Searching and SortingChapter 14 Searching and Sorting
Chapter 14 Searching and Sorting
 
Data Structures- Part4 basic sorting algorithms
Data Structures- Part4 basic sorting algorithmsData Structures- Part4 basic sorting algorithms
Data Structures- Part4 basic sorting algorithms
 
Quick and radix sort
Quick and radix sortQuick and radix sort
Quick and radix sort
 
Presentation
PresentationPresentation
Presentation
 

Viewers also liked

Quick sort algo analysis
Quick sort algo analysisQuick sort algo analysis
Quick sort algo analysis
Nargis Ehsan
 
James Metcalfe's May Real Estate Update
James Metcalfe's May Real Estate Update James Metcalfe's May Real Estate Update
James Metcalfe's May Real Estate Update
James Metcalfe
 
Smart Service@KKU Library
Smart Service@KKU LibrarySmart Service@KKU Library
Smart Service@KKU Library
Gritiga Soothorn
 
Unlocking Social CRM for your Organisation (Keynote)
Unlocking Social CRM for your Organisation (Keynote)Unlocking Social CRM for your Organisation (Keynote)
Unlocking Social CRM for your Organisation (Keynote)
Joakim Nilsson
 
庄琪冬 107081018 工业设计工学071
庄琪冬 107081018 工业设计工学071庄琪冬 107081018 工业设计工学071
庄琪冬 107081018 工业设计工学071zust
 
Technology For ESL
Technology For ESLTechnology For ESL
Technology For ESL
johnnakp
 
Trend2014del1 slut.key
Trend2014del1 slut.keyTrend2014del1 slut.key
Trend2014del1 slut.key
Goran Adlen
 
презентация Microsoft Power Point
презентация Microsoft Power Pointпрезентация Microsoft Power Point
презентация Microsoft Power Pointnatysik
 
Quick Start: Rails
Quick Start: RailsQuick Start: Rails
Quick Start: Rails
David Keener
 
Mayanclothadvancedtechniques2010
Mayanclothadvancedtechniques2010Mayanclothadvancedtechniques2010
Mayanclothadvancedtechniques2010
codewarrior congrejo
 
Mayacompositeuserguide
MayacompositeuserguideMayacompositeuserguide
Mayacompositeuserguide
codewarrior congrejo
 
Инвестор - 10 години в 10 минути
Инвестор - 10 години в 10 минутиИнвестор - 10 години в 10 минути
Инвестор - 10 години в 10 минути
hrisimashkova
 
Summerhill
SummerhillSummerhill
Summerhillbertafv
 
Assig 1 5 1920 S
Assig 1 5 1920 SAssig 1 5 1920 S
Assig 1 5 1920 S
frankwerner11
 
Summerhill
SummerhillSummerhill
Summerhillbertafv
 
The Pillars Of Self Mastery
The Pillars Of Self MasteryThe Pillars Of Self Mastery
The Pillars Of Self Mastery
professor shamshad
 
5 60 Kumarasiri VP and seedling tea
5 60 Kumarasiri VP and seedling tea5 60 Kumarasiri VP and seedling tea
Containers virtaulization and docker
Containers virtaulization and dockerContainers virtaulization and docker
Containers virtaulization and docker
Luqman Shareef
 

Viewers also liked (20)

Quick sort algo analysis
Quick sort algo analysisQuick sort algo analysis
Quick sort algo analysis
 
Prueba 1
Prueba 1Prueba 1
Prueba 1
 
James Metcalfe's May Real Estate Update
James Metcalfe's May Real Estate Update James Metcalfe's May Real Estate Update
James Metcalfe's May Real Estate Update
 
Smart Service@KKU Library
Smart Service@KKU LibrarySmart Service@KKU Library
Smart Service@KKU Library
 
Unlocking Social CRM for your Organisation (Keynote)
Unlocking Social CRM for your Organisation (Keynote)Unlocking Social CRM for your Organisation (Keynote)
Unlocking Social CRM for your Organisation (Keynote)
 
庄琪冬 107081018 工业设计工学071
庄琪冬 107081018 工业设计工学071庄琪冬 107081018 工业设计工学071
庄琪冬 107081018 工业设计工学071
 
Technology For ESL
Technology For ESLTechnology For ESL
Technology For ESL
 
Trend2014del1 slut.key
Trend2014del1 slut.keyTrend2014del1 slut.key
Trend2014del1 slut.key
 
презентация Microsoft Power Point
презентация Microsoft Power Pointпрезентация Microsoft Power Point
презентация Microsoft Power Point
 
Quick Start: Rails
Quick Start: RailsQuick Start: Rails
Quick Start: Rails
 
Mayanclothadvancedtechniques2010
Mayanclothadvancedtechniques2010Mayanclothadvancedtechniques2010
Mayanclothadvancedtechniques2010
 
Mayacompositeuserguide
MayacompositeuserguideMayacompositeuserguide
Mayacompositeuserguide
 
Инвестор - 10 години в 10 минути
Инвестор - 10 години в 10 минутиИнвестор - 10 години в 10 минути
Инвестор - 10 години в 10 минути
 
Summerhill
SummerhillSummerhill
Summerhill
 
Assig 1 5 1920 S
Assig 1 5 1920 SAssig 1 5 1920 S
Assig 1 5 1920 S
 
Summerhill
SummerhillSummerhill
Summerhill
 
The Pillars Of Self Mastery
The Pillars Of Self MasteryThe Pillars Of Self Mastery
The Pillars Of Self Mastery
 
family
familyfamily
family
 
5 60 Kumarasiri VP and seedling tea
5 60 Kumarasiri VP and seedling tea5 60 Kumarasiri VP and seedling tea
5 60 Kumarasiri VP and seedling tea
 
Containers virtaulization and docker
Containers virtaulization and dockerContainers virtaulization and docker
Containers virtaulization and docker
 

Similar to Lect11 Sorting

Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"
Ra'Fat Al-Msie'deen
 
Insertion sort bubble sort selection sort
Insertion sort bubble sort  selection sortInsertion sort bubble sort  selection sort
Insertion sort bubble sort selection sort
Ummar Hayat
 
Sortings .pptx
Sortings .pptxSortings .pptx
Sortings .pptx
MuhammadSheraz836877
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
pppepito86
 
Lecture 13 data structures and algorithms
Lecture 13 data structures and algorithmsLecture 13 data structures and algorithms
Lecture 13 data structures and algorithms
Aakash deep Singhal
 
Lecture_14Sorting.pptx
Lecture_14Sorting.pptxLecture_14Sorting.pptx
Lecture_14Sorting.pptx
jeevankjeevan
 
Sorting
SortingSorting
Sorting
Zaid Shabbir
 
Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.
NikhilSoni177492
 
Insertion sort analysis
Insertion sort analysisInsertion sort analysis
Insertion sort analysis
Kumar
 
sorting1.pptx
sorting1.pptxsorting1.pptx
sorting1.pptx
AJAYVISHALRP
 
Priority queues
Priority queuesPriority queues
Priority queues
Priyanka Rana
 
Datastructure tree
Datastructure treeDatastructure tree
Datastructure tree
rantd
 
Top school in delhi ncr
Top school in delhi ncrTop school in delhi ncr
Top school in delhi ncr
Edhole.com
 
Unit 7 sorting
Unit 7   sortingUnit 7   sorting
Unit 7 sorting
kalyanineve
 
Lec1
Lec1Lec1
Algorithms lecture 3
Algorithms lecture 3Algorithms lecture 3
Algorithms lecture 3
Mimi Haque
 
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
Tosin Amuda
 
Week09
Week09Week09
Week09
hccit
 
CSPC/ PPS Sorting methods
CSPC/ PPS Sorting methodsCSPC/ PPS Sorting methods
CSPC/ PPS Sorting methods
Ankur Srivastava
 
Introduction to MatLab programming
Introduction to MatLab programmingIntroduction to MatLab programming
Introduction to MatLab programming
Damian T. Gordon
 

Similar to Lect11 Sorting (20)

Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"
 
Insertion sort bubble sort selection sort
Insertion sort bubble sort  selection sortInsertion sort bubble sort  selection sort
Insertion sort bubble sort selection sort
 
Sortings .pptx
Sortings .pptxSortings .pptx
Sortings .pptx
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
 
Lecture 13 data structures and algorithms
Lecture 13 data structures and algorithmsLecture 13 data structures and algorithms
Lecture 13 data structures and algorithms
 
Lecture_14Sorting.pptx
Lecture_14Sorting.pptxLecture_14Sorting.pptx
Lecture_14Sorting.pptx
 
Sorting
SortingSorting
Sorting
 
Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.
 
Insertion sort analysis
Insertion sort analysisInsertion sort analysis
Insertion sort analysis
 
sorting1.pptx
sorting1.pptxsorting1.pptx
sorting1.pptx
 
Priority queues
Priority queuesPriority queues
Priority queues
 
Datastructure tree
Datastructure treeDatastructure tree
Datastructure tree
 
Top school in delhi ncr
Top school in delhi ncrTop school in delhi ncr
Top school in delhi ncr
 
Unit 7 sorting
Unit 7   sortingUnit 7   sorting
Unit 7 sorting
 
Lec1
Lec1Lec1
Lec1
 
Algorithms lecture 3
Algorithms lecture 3Algorithms lecture 3
Algorithms lecture 3
 
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
 
Week09
Week09Week09
Week09
 
CSPC/ PPS Sorting methods
CSPC/ PPS Sorting methodsCSPC/ PPS Sorting methods
CSPC/ PPS Sorting methods
 
Introduction to MatLab programming
Introduction to MatLab programmingIntroduction to MatLab programming
Introduction to MatLab programming
 

Recently uploaded

Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
alexjohnson7307
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Tatiana Kojar
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
Hiike
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
Data Hops
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 

Recently uploaded (20)

Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 

Lect11 Sorting

  • 1. 1302251 Data Structures and Algorithms Lecture 11 Sorting Aj. Khwunta Kirimasthong School of Information Technology Mae Fah Luang University
  • 2. Outline  Sorting Concept  Sorting Algorithm  Selection Sort  Insertion Sort  Merge Sort  Quick Sort 2
  • 3. Sorting Concept  Sorting is the operation of arranging data in some given order, such as  Ascending  the dictionary, the telephone book  Descending  grade-point average for honor students  The sorted data can be numerical data or character data.  Sorting is one of the most common data-processing applications. 3
  • 4. Sorting Concept (Cont.)  Sorting problem Let A be a sequence of n elements. Sorting A refers to the operation of rearranging the content of A so that they are increasing in order. Input: A: the sequence of n numbers ( a1 , a 2 , ..., a n ) Output: A: the reordering ( a1 , a 2 ,..., a n ) of the input sequence such that a1 a2 an 4
  • 5. Selection Sort  One of basic sorting algorithms  Selection Sort works as follows:  First, find the smallest elements in the data sequence and exchange it with the element in the first position,  Then, find the second smallest element and exchange it with the element in the second position and  Continue in this way until the entire sequence is sorted. 5
  • 6. Selection Sort Example 1 2 3 4 5 6 1 2 3 4 5 6 A 5 2 4 6 1 3 (1) A 1 2 4 6 5 3 1 2 3 4 5 6 (2) A 1 2 4 6 5 3 1 2 3 4 5 6 (3) A 1 2 3 6 5 4 1 2 3 4 5 6 (4) A 1 2 3 4 5 6 1 2 3 4 5 6 (5) A 1 2 3 4 5 6 1 2 3 4 5 6 (6) A 1 2 3 4 5 6 6
  • 7. Selection Sort Algorithm Algorithm SelectionSort(A,n) Input: A: a sequence of n elements n: the size of A Output: A: a sorted sequence in ascending order for i = 1 to n min = i for j = i+1 to n if A[j] < A[min] then min = j Swap(A,min,i) 7
  • 8. Selection Sort Algorithm (Cont.) Algorithm: Swap(A,min,i) Input: A : a sequence of n elements min: the position of the minimum value of A while considers at index i of A i: the considered index of A Output: exchange A[i] and A[min] temp = a[min] a[min] = a[i] a[i] = temp 8
  • 9. Selection Sort Analysis  For i = 1, there are _(n-1)_ comparisons to find the first smallest element.  For i = 2, there are _(n-2)_ comparisons to find the second smallest element, and so on.  Accordingly, n 1 (n-1) + (n-2) + (n-3) + … + 2 + 1 = i = n(n-1)/2 i 1  The best case running time is ___ (n2)__  The worst case running time is __ O(n2)__ 9
  • 10. Insertion Sort  To solve the sorting problem  Insertion sort algorithm is almost as simple as selection sort but perhaps more flexible.  Insertion sort is the method people often use for sorting a hand of cards. 10
  • 11. Insertion Sort (Cont.)  Insertion sort uses an incremental approach: having the sorted subarray A[1…j-1], we insert the single element A[ j ] into its proper place and then we will get the sorted subarray A[ 1…j ] pick up Sorted order Unsorted order 11
  • 12. Insertion Sort Example 1 2 3 4 5 6 5 2 4 6 1 3 key = A[j] 1 2 3 4 5 6 (1) A 5 2 4 6 1 3 key 2 1 2 3 4 5 6 (2) A 2 5 4 6 1 3 key 4 1 2 3 4 5 6 (3) A 2 4 5 6 1 3 key 6 in-place sorted 12
  • 13. Insertion Sort Example (Cont.) 1 2 3 4 5 6 (4) A 2 4 5 6 1 3 key 1 1 2 3 4 5 6 (5) A 1 2 4 5 6 3 key 3 1 2 3 4 5 6 (6) A 1 2 3 4 5 6 in-place sorted 13
  • 14. Insertion Sort Algorithm Algorithm: INSERTION-SORT(A) Input: A : A sequence of n numbers Output: A : A sorted sequence in increasing order of array A for j = 2 to length(A) key = A[j] //Insert A[j] into the sorted sequence A[1…j-1] i = j-1 while i > 0 and A[i] > key A[i+1] = A[i] i = i-1 A[i+1] = key 14
  • 15. Insertion Sort Analysis  The running – time of INSERTION-SORT depends on the size of input. 15
  • 16. Insertion Sort Analysis (cont.) INSERTION-SORT(A) cost times 1. for j = 2 to length(A) c1 n 2. key = A[j] c2 n-1 3. //Insert A[j] into the sorted sequence A[1…j-1] 0 n-1 4. i = j-1 c4 n-1 n 5. while i > 0 and A[i] > key c5 tj j 2 n 6. A[i+1] = A[i] c6 (t j 1) j 2 n 7. i = i-1 c7 (t j 1) j 2 8. A[i+1] = key c8 n-1 16
  • 17. Analysis of Insertion Sort (Cont.)  To Compute the total running time of INSERTION- SORT, T ( n ) n T (n) c1 n c2 (n 1) 0(n 1) c4 (n 1) c5 tj j 2 n n c6 (t j 1) c7 (t j 1) c8 ( n 1) j 2 j 2 17
  • 18. Analysis of Insertion Sort (Cont.)  Best – case  If input array is already sorted. Thus tj = 1 T(n) = c1n+c2(n-1)+(0)(n-1)+c4(n-1)+c5(n-1)+c6(0)+c7(0)+c8(n-1) = (c1+c2+c3+c4+c5+c8)n - (c2+c3+c4+c5+c8) an + b for constant a and b Base-case running time of INSERTION-SORT is (n) 18
  • 19. Analysis of Insertion Sort (Cont.)  Worse – case  If input array is in reverse sorted order. Thus tj = j n(n 1) T (n) c1 n c2 (n 1) c4 (n 1) c5 1 2 (n 1) n (n 1) n c6 c7 c8 ( n 1) 2 2 c5 c6 c6 2 c5 c6 c7 T (n) n c1 c2 c4 c8 n 2 2 2 2 2 2 (c2 c4 c5 c8 ) an 2 bn c for constant a, b and c 2 Worse-case running time of INSERTION-SORT is (n ) 19
  • 20. Analysis of Insertion Sort (Cont.)  Worse – case (Cont.)  If input array is in reverse sorted order. Thus tj = j n n n n(n 1) n(n 1) j tj j 1 j 1 2 j 2 j 2 2 n n (n 1)(( n 1) 1) (n 1) n (t j 1) (j 1) (1 1) j 2 j 2 2 2 20
  • 21. Divide and Conquer Approach Merge Sort Quick Sort
  • 22. Divide-and-Conquer Approach  The divide-and-conquer approach involves three steps at each level of the recursion:  Divide the problem into a number of sub-problems that are similar to the original problem but smaller in size.  Conquer the sub-problems by solving them recursively.  Combine the solution of subproblems into the solution for the original problem. 22
  • 23. Merge Sort  The Merge Sort algorithm closely follows the divide-and-conquer approach. It operates as follows,  Divide: Divide the n-element sequence to be sorted into two subsequences of n/2 elements each.  Conquer: Sort the two subsequences recursively using merge sort  Combine: Merge the two sorted subsequences to produce the sorted solution. 23
  • 24. Merge Sort (Cont.)  The recursion “bottom out” when the sequence to be sorted has length 1, in which case there is no work to be done, since every sequence of length 1 is already in sorted order. 24
  • 25. Merge Sort Example DIVIDE & 0 1 2 3 4 5 CONQUER A 5 2 4 6 1 3 0 1 2 3 4 5 5 2 4 6 1 3 0 1 2 3 4 5 5 2 4 6 1 3 0 1 3 4 5 2 6 1 25
  • 26. Merge Sort Example (cont.) 0 1 2 3 4 5 COMBINE A 1 2 3 4 5 6 0 1 2 3 4 5 2 4 5 1 3 6 0 1 2 3 4 5 2 5 4 1 6 3 0 1 3 4 5 2 6 1 26
  • 27. Merge Sort Algorithm Algorithm MergeSort( A, p, q ) Input: A: a sequence of n elements p: the beginning index of A q: the last index of A Output: A: a sorted sequence of n elements if(p < q) then r = floor((p+q)/2) MergeSort(A,p,r) MergeSort(A,r+1,q) Merge(A,p,r,q) 27
  • 28. Algo Merge(A,p,r,q) Input: A, p, r, q : a sorted subsequences A[p…r] and A[r+1…q] Output: A: a sorted sequence A[p…q] let i=p, k=p, j=r+1 while (i ≤ r) and (j ≤ q) if (A[i] ≤ A[j]) then B[k] = A[i] k++ i++ else B[k] = A[j] k=k+1 j=j+1 if (i>r) then /* If the maximum value of left subsequence is less than the right subsequence */ while(j ≤ q) B[k] = A[j] k++ j++ else if(j > q) then /* If the maximum value of left subsequence is gather than the right subsequence */ while(i ≤ r) B[k] = A[i] k++ i++ for k = p to q A[k] = b[k] 28
  • 29. Merge Sort Analysis  The best case running time is _ (n log n)_  The worst case running time is _ O(n log n) _ 29
  • 30. Quick Sort  Quick Sort, likes merge sort, is based on the divide-and-conquer approach.  To sort an array A[p…r]  Divide: Partition (rearrange) the array A[p…r] into two subarray A[p…q -1] and subarray A[q+1…r] such that:  Each element of A[p…q -1] is less than or equal to A[q]  Each element of A[q+1…r] is greater than A[q] 30
  • 31. Quick Sort (Cont.)  To sort sorting an array A[p…r] (cont.)  Conquer: Sort the two subarray A[p…q -1] and A[q+1…r] by recursive calls to QuickSort.  Combine: Since the subarrays are sorted in place, no work is needed to combine them: the entire array A[p…r] is now sorted. 31
  • 32. Quick Sort Example 0 1 2 3 4 5 A 5 2 4 6 1 3 32
  • 33. Quick Sort Algorithm Algo QuickSort(A, p, r) Input: A: A sequence of n numbers p: The first index of A r: The last index of A Output: A: A sorted sequence in increasing order of array A • Rearrange the subarray if (p < r) then A[p…r] in place. • The elements that is less q = Partition(A,p,r) than A[q] are placed at the left side of A[q] and QuickSort(A,p,q-1) • The elements that is greater than A[q] are placed QuickSort(A,q+1,r) at the right side of A[q]. 33
  • 34. Quick Sort Algorithm (Cont.) Algo Partition(A, p, r) Input: A: A sequence of n numbers p: The first index of A r: The last index of A Output: A: The rearranged subarray A[p…r] key = A[r] i=p–1 for j = p to r -1 if A[ j ] ≤ key then i = i+1 exchange A[i] and A[j] exchange A[i+1] and key return i+1 34
  • 35. Quick Sort Analysis  The best case running time is _ (n log n)_  The worst case running time is _ O(n2)_ 35
  • 36. Q&A