SlideShare a Scribd company logo
Introduction to Sorting Techniques

Objectives
In this lesson, you will learn to:
 State the different sorting techniques
 State the complexities in the different sorting
  algorithms




                        Introduction to Sorting Techniques/Lesson 6/Slide 1 of 40
  ©NIIT
Introduction to Sorting Techniques

 Sorting
  Sorting and searching are fundamental operations
   performed on data
  Sorting refers to operation of arranging data in given
   order
  Searching refers to finding a location of given item
  Algorithm chosen depends on operation to be
   performed on data




                     Introduction to Sorting Techniques/Lesson 6/Slide 2 of 40
  ©NIIT
Introduction to Sorting Techniques

 Sorting (Contd..)
  Some sorting algorithms in use are:
       Bubble sort
       Selection sort
       Insertion sort
       Merge sort
       Quick sort




                         Introduction to Sorting Techniques/Lesson 6/Slide 3 of 40
  ©NIIT
Introduction to Sorting Techniques

 Bubble Sort
  Take a list of numbers consisting of n elements
  This algorithm requires to traverse the list n-1 times
  Traversing the entire list once is called a pass
  For a list of n numbers there will be n-1 passes




                     Introduction to Sorting Techniques/Lesson 6/Slide 4 of 40
  ©NIIT
Introduction to Sorting Techniques

 Bubble Sort (Contd..)
  Step 1:
       Compare first two elements and arrange them
       Compare second and third element and arrange
        them
       Compare fourth and fifth and arrange them
       Compare n-1 with nth element and arrange them
  Step 2:
       Repeat step 1 with one less comparison



                     Introduction to Sorting Techniques/Lesson 6/Slide 5 of 40
  ©NIIT
Introduction to Sorting Techniques

 Bubble Sort (Contd..)
  Step 3:
       Repeat step 1 with two less comparison
  Step N:
       This step will have only one comparison
 Example:
  Sort 5, 2, 6, 7, 3 using bubble sort




                     Introduction to Sorting Techniques/Lesson 6/Slide 6 of 40
  ©NIIT
Introduction to Sorting Techniques

 Bubble Sort (Contd..)
  Pass 1: Compare first and second element. If X1 
   X2 interchange as 2, 5, 6, 7, 3
             Compare X2 with X3. If X2  X3 interchange
              else the list remains as it is
             Compare X3 with X4. Since X3  X4, list
              remains the same




                        Introduction to Sorting Techniques/Lesson 6/Slide 7 of 40
  ©NIIT
Introduction to Sorting Techniques

 Bubble Sort (Contd..)
       Compare X4 with X5. Since X4  X5 interchange
        happens
                 2,       5,       6,       3,       7
  At the end of this pass, the largest number is placed
   at the last position. Let us see what happens for the
   remainder of passes
  Pass 2:
                2     5        6        3        7

                2     5        6        3        7

                2     5        3        6        7


                      Introduction to Sorting Techniques/Lesson 6/Slide 8 of 40
  ©NIIT
Introduction to Sorting Techniques

 Bubble Sort (Contd.)
  Pass 3 :
              2   5   3    6     7

              2   3   5    6     7




  Pass 4 :
              2   3   5     6     7




  All the elements are sorted after the fourth pass


                      Introduction to Sorting Techniques/Lesson 6/Slide 9 of 40
  ©NIIT
Introduction to Sorting Techniques

 Problem Statement 6.D.1
     Write a program to store 10 student marks. After
     implementing the bubble sorting, display the contents
     of sorted array.




                      Introduction to Sorting Techniques/Lesson 6/Slide 10 of
  ©NIIT
                                                                          40
Introduction to Sorting Techniques

 Selection Sort
  The algorithm finds the smallest element and puts it in
   first position
  Then finds second smallest and puts in the second
   position
  This is done for n-1 times




                      Introduction to Sorting Techniques/Lesson 6/Slide 11 of
  ©NIIT
                                                                          40
Introduction to Sorting Techniques

 Selection Sort (Contd..)
  Consider an array Num of n elements
  Step 1:
       Search for location of smallest element
       Interchange the contents with the first location in
        the array
  Step 2:
       Search for smallest element in sublist of n-1
        elements
       Interchange with the contents of the second
        location
                        Introduction to Sorting Techniques/Lesson 6/Slide 12 of
  ©NIIT
                                                                            40
Introduction to Sorting Techniques

 Selection Sort (Contd..)
  Step n:
       Search for the smaller between n-1 and n and
        interchange
  Take a variable MIN to contain the current smallest
   value
       A variable LOC to contain the location of the
        smallest value
       Traverse the list comparing minimum with other
        elements



                       Introduction to Sorting Techniques/Lesson 6/Slide 13 of
  ©NIIT
                                                                           40
Introduction to Sorting Techniques

 Selection Sort (Contd..)
       If MIN  = Num[i] then MIN=Num[i] else move to
        next location
  MIN will contain the smallest value after comparison
   with the last element
  LOC will contain the location of MIN




                      Introduction to Sorting Techniques/Lesson 6/Slide 14 of
  ©NIIT
                                                                          40
Introduction to Sorting Techniques

 Selection Sort (Contd..)
 This procedure finds the smallest of the elements among
   NUM[I], NUM[I+1], . .. , NUM[N]
  MINIMUM(NUM,I,N,LOC)
      1. Set MIN=NUM[I] and LOC = I
      2.   Repeat for J = I + 1, I + 2 , . . . , N
              If MIN  NUM[J]
                    then set MIN = NUM[J] and LOC = J
      3.   Return



                         Introduction to Sorting Techniques/Lesson 6/Slide 15 of
  ©NIIT
                                                                             40
Introduction to Sorting Techniques

 Selection Sort (Contd..)
 Algorithm:

 This algorithm sorts an array with N elements.
 4. Repeat steps 2 and 3 for I=1,2,3,..., N
 5. Call MINIMUM(NUM,I,N, LOC)
 6. [Interchange Num[I] with NUM[LOC]]




                      Introduction to Sorting Techniques/Lesson 6/Slide 16 of
  ©NIIT
                                                                          40
Introduction to Sorting Techniques

 Selection Sort (Contd.)
 Set TEMP= NUM[I],
 NUM[I] = NUM[LOC]
 NUM[LOC]=TEMP.
 [loop of step 1 ends]
 6. Exit




                         Introduction to Sorting Techniques/Lesson 6/Slide 17 of
  ©NIIT
                                                                             40
Introduction to Sorting Techniques

 Selection Sort (Contd..)
   Pass     Num[1]   Num[2]         Num[3]        Num[4]       Num[5]        Num[6]


I=1 LOC=5   35        57              30           76            3             10


I=2 LOC=6   3         57              30           76            35            10


I=3 LOC=3   3         10              30           76            35            57


I=4 LOC=5   3         10              30           76            35            57


I=5 LOC=6   3         10              30           35            76            57


Sorted      3         10              30           35            57            76




                           Introduction to Sorting Techniques/Lesson 6/Slide 18 of
  ©NIIT
                                                                               40
Introduction to Sorting Techniques

 Insertion Sort
  An element is put into its correct position with each
   iteration of the main loop, relative to the sub-array that
   has already been processed
  Inserts each element to its proper location
  Frequently used with small number of elements




                       Introduction to Sorting Techniques/Lesson 6/Slide 19 of
  ©NIIT
                                                                           40
Introduction to Sorting Techniques

 Insertion Sort (Contd..)
 The following steps are performed
  Pass 1: Num[1] by itself is sorted
  Pass 2: Num[2] is inserted either before or after
   Num[1] , such that Num[1] and Num[2] are sorted
  Pass 3: Num[3] is inserted into its proper place, i.e.
   before Num[1], between Num[1] and Num[2], or after
   Num[2], such that Num[1], Num[2], Num[3] are sorted




                     Introduction to Sorting Techniques/Lesson 6/Slide 20 of
  ©NIIT
                                                                         40
Introduction to Sorting Techniques

 Insertion Sort (Contd..)
  ....    ....   ....
  ....    ....   ....
 Pass N: Num[n] is inserted into its proper place such
 that Num[1], Num[2],... ,Num[n] is sorted




                        Introduction to Sorting Techniques/Lesson 6/Slide 21 of
  ©NIIT
                                                                            40
Introduction to Sorting Techniques

 Insertion Sort (Contd..)
     Pass   Num[1]   Num[2]    Num[3]    Num[4]     Num[5]    Num[6]    Num[6]

  K=1         -∞     35         57         30         76        3         10

  K=2         -∞     35         57         30         76        3          10

  K=3         -∞     35         57         30         76        3          10

  K=4         -∞     30         35         57         76        3          10

  K=5         -∞     30         35         57         76        3          10

  K=6         -∞     3          30         35         57        76         10

  Sorted      -∞     3          10         30         35        57         76




                          Introduction to Sorting Techniques/Lesson 6/Slide 22 of
  ©NIIT
                                                                              40
Introduction to Sorting Techniques

 Insertion Sort (Contd..)
 Algorithm:

   INSERTION (NUM,N)
   The algorithm sorts the array NUM with N elements
          1.   Set Num[0] = -∞ [ Initialize the sentinel element]
          2.   Repeat steps 3 to 5 for K=2,3,4,... , N
          3.   Set TEMP=Num[K] and PTR =K-1




                            Introduction to Sorting Techniques/Lesson 6/Slide 23 of
  ©NIIT
                                                                                40
Introduction to Sorting Techniques

 Insertion Sort (Contd..)
          1.   Do while TEMP  Num[PTR]
               a.   Set Num[PTR+1] = Num[PTR]
               b.   Set PTR=PTR – 1
                    (end of loop)
          1.   Set Num[PTR+1]=TEMP
                (end of loop)
          1.   Return




                            Introduction to Sorting Techniques/Lesson 6/Slide 24 of
  ©NIIT
                                                                                40
Introduction to Sorting Techniques

 Problem Statement 6.P.1
     Write a function implementing insertion sorting.




                       Introduction to Sorting Techniques/Lesson 6/Slide 25 of
  ©NIIT
                                                                           40
Introduction to Sorting Techniques

 Merge Sort
 Step 1:
   Split the list into sublists of equal size
 Step 2:
   Sort them separately
 Step 3:
   Merge them together




                        Introduction to Sorting Techniques/Lesson 6/Slide 26 of
  ©NIIT
                                                                            40
Introduction to Sorting Techniques

 Merge Sort (Contd..)
 Example: Let us sort 53, 10,30,76,3,57,24 using merge
 sort
 Step 1:
   Chop them into pairs and sort them
          53, 10     30, 76           3, 57             24
 Step 2:
   Merge the pairs to obtain the following sorted sublists
          10,53    30,76      3,57 24



                       Introduction to Sorting Techniques/Lesson 6/Slide 27 of
  ©NIIT
                                                                           40
Introduction to Sorting Techniques

 Merge Sort (Contd..)
 Step 3:
   Merge the sorted sublists to obtain a single sorted
    array
          3, 10, 24, 30, 53, 57, 76
 The original array is now sorted




                        Introduction to Sorting Techniques/Lesson 6/Slide 28 of
  ©NIIT
                                                                            40
Introduction to Sorting Techniques

  Quick Sort
   We arrange the list in some logical order
   Algorithm is divide and conquer type
   Sorting is reduced to sorting two smaller subsets
   Reduction step finds the final position of one number




                      Introduction to Sorting Techniques/Lesson 6/Slide 29 of
  ©NIIT
                                                                          40
Introduction to Sorting Techniques

 Quick Sort (Contd..)
  Step1:
       Take first element as key element
       Scan right to left for an element less than key
        element
       Interchange positions of the elements
  Step 2:
       Scan right to left for element greater than key
        element
       Interchange positions of the elements

                        Introduction to Sorting Techniques/Lesson 6/Slide 30 of
  ©NIIT
                                                                            40
Introduction to Sorting Techniques

 Quick Sort (Contd..)
  Step 3:
       Continue step 1 and step 2 till
          ® all   element in right are greater than key
          ® all   element in left are less than key
  The key element will be placed in its correct position
  Repeat reduction step for each sub list with two or
   more elements




                           Introduction to Sorting Techniques/Lesson 6/Slide 31 of
  ©NIIT
                                                                               40
Introduction to Sorting Techniques

 Quick Sort (Contd..)
 Example:       35        57        30      76      3        10


  In this example we take the number 35 as the key

      STEP 1:        10        57          30        76                3   35


      STEP 2:        10        35          30        76                3   57


      STEP 3:        10        3           30        76           35       57


      STEP 3:        10        3           30        35           76       57




  35 is correctly placed in its final position
                                   Introduction to Sorting Techniques/Lesson 6/Slide 32 of
  ©NIIT
                                                                                       40
Introduction to Sorting Techniques

 Problem Statement 6.D.2
     Write a program to store 10 numbers in an array.
     After implementing quick sorting, display the contents
     of the sorted array.




                       Introduction to Sorting Techniques/Lesson 6/Slide 33 of
  ©NIIT
                                                                           40
Introduction to Sorting Techniques

 Complexities
 For bubble sort
   The number of comparisons
   f(n) = (n-1) + (n-2) + (n-3) +...+ 2 + 1

               = n(n-1)
                    2


            = n2 + O(n)                      = O(n2)
              2


                        Introduction to Sorting Techniques/Lesson 6/Slide 34 of
  ©NIIT
                                                                            40
Introduction to Sorting Techniques

 Complexities (Contd..)
 For quick sort
   Worst case (when the list is already sorted)
          f(n) = n + (n-1) + (n-2) +...+2 + 1
                 = n(n-1)      = n2 + O(n)                             = O(n2)
                    2            2
   Average case
          ® In   kth level finds the location of 2K-1 elements
            f(n) = O(n log n)


                            Introduction to Sorting Techniques/Lesson 6/Slide 35 of
  ©NIIT
                                                                                40
Introduction to Sorting Techniques

 Complexities (Contd..)
 For selection sort
   Number of comparisons depends on original order of
    elements
   There are n-1 comparisons in pass1
   There are n-2 comparisons in pass 2
          f(n) = (n-1) + (n-2) + (n-3) +...+ 2 + 1
              = n(n-1)      = n2 + O(n)             = O(n2)
                  2           2



                         Introduction to Sorting Techniques/Lesson 6/Slide 36 of
  ©NIIT
                                                                             40
Introduction to Sorting Techniques

 Complexities (Contd..)
 For insertion sort
   Worst case occurs when the array is in the reverse
    order
   Inner loop executes maximum number K-1 of
    comparisons
          f(n) = 1+ 2 + . . . + (n-1)        = n(n-1)           = O(n2)
                                                 2




                          Introduction to Sorting Techniques/Lesson 6/Slide 37 of
  ©NIIT
                                                                              40
Introduction to Sorting Techniques

 Complexities (Contd..)
   Average case
   There will be approximately (K-1)/2 comparisons in
    the inner loop
          f(n) = 1+ 2+ 3+ . . .+ (n-1)            = n(n-1) = O(n2)
                 2 2 2             2                   4




                         Introduction to Sorting Techniques/Lesson 6/Slide 38 of
  ©NIIT
                                                                             40
Introduction to Sorting Techniques

Summary
In this lesson, you learned that:
 Different types of sorting are:
      Bubble sort
      Selection sort
      Insertion sort
      Merge sort
      Quick sort




                          Introduction to Sorting Techniques/Lesson 6/Slide 39 of
    ©NIIT
                                                                              40
Introduction to Sorting Techniques

Summary (Contd..)
 The time required to execute bubble sort algorithm is
  proportional to n2, where n is the number of inputs
 The number of comparisons in a selection sort is
  independent of the original order of the elements
 The insertion sort is a very slow algorithm when the
  number of elements in the array is very large
 The Quick sort algorithm has a worst case running
  time of order n2/2




                      Introduction to Sorting Techniques/Lesson 6/Slide 40 of
  ©NIIT
                                                                          40

More Related Content

Viewers also liked

Amenazas contra compañeros de la ucizoni
Amenazas contra compañeros de la ucizoniAmenazas contra compañeros de la ucizoni
Amenazas contra compañeros de la ucizoni
UCIZONI AC
 
Conozco y limpio mis dientes (3) madiay
Conozco y limpio mis dientes (3)  madiayConozco y limpio mis dientes (3)  madiay
Conozco y limpio mis dientes (3) madiay
MADIAY
 
05 qmds2005 session07
05 qmds2005 session0705 qmds2005 session07
05 qmds2005 session07
Niit Care
 
品座
品座品座
品座
secondless
 
Presentatie framingham-bij-ouderen-finaal
Presentatie framingham-bij-ouderen-finaalPresentatie framingham-bij-ouderen-finaal
Presentatie framingham-bij-ouderen-finaal
Bo Gevers
 
Ekonomi sem 2
Ekonomi sem  2Ekonomi sem  2
Ekonomi sem 2
putrisagut
 
Team Power Point
Team Power PointTeam Power Point
Team Power Point
TEAM Industries
 
Ideas de negocio globales para internacionalización de startups.
Ideas de negocio globales para internacionalización de startups. Ideas de negocio globales para internacionalización de startups.
Ideas de negocio globales para internacionalización de startups.
Carmen Urbano
 
Categoria
CategoriaCategoria
Categoria
Regina Gandara
 
Internacionalización en red. Redes sociales e internacionalización 360
Internacionalización en red. Redes sociales e internacionalización 360Internacionalización en red. Redes sociales e internacionalización 360
Internacionalización en red. Redes sociales e internacionalización 360
Carmen Urbano
 
Project Management Article Transport Magazine dual language rev6
Project Management Article Transport Magazine dual language rev6Project Management Article Transport Magazine dual language rev6
Project Management Article Transport Magazine dual language rev6
Rene Cruz
 
Angka indeks statistika
Angka indeks statistikaAngka indeks statistika
Angka indeks statistika
Rizki NoVitha
 

Viewers also liked (13)

Amenazas contra compañeros de la ucizoni
Amenazas contra compañeros de la ucizoniAmenazas contra compañeros de la ucizoni
Amenazas contra compañeros de la ucizoni
 
Conozco y limpio mis dientes (3) madiay
Conozco y limpio mis dientes (3)  madiayConozco y limpio mis dientes (3)  madiay
Conozco y limpio mis dientes (3) madiay
 
05 qmds2005 session07
05 qmds2005 session0705 qmds2005 session07
05 qmds2005 session07
 
品座
品座品座
品座
 
Presentatie framingham-bij-ouderen-finaal
Presentatie framingham-bij-ouderen-finaalPresentatie framingham-bij-ouderen-finaal
Presentatie framingham-bij-ouderen-finaal
 
Ekonomi sem 2
Ekonomi sem  2Ekonomi sem  2
Ekonomi sem 2
 
Doc2
Doc2Doc2
Doc2
 
Team Power Point
Team Power PointTeam Power Point
Team Power Point
 
Ideas de negocio globales para internacionalización de startups.
Ideas de negocio globales para internacionalización de startups. Ideas de negocio globales para internacionalización de startups.
Ideas de negocio globales para internacionalización de startups.
 
Categoria
CategoriaCategoria
Categoria
 
Internacionalización en red. Redes sociales e internacionalización 360
Internacionalización en red. Redes sociales e internacionalización 360Internacionalización en red. Redes sociales e internacionalización 360
Internacionalización en red. Redes sociales e internacionalización 360
 
Project Management Article Transport Magazine dual language rev6
Project Management Article Transport Magazine dual language rev6Project Management Article Transport Magazine dual language rev6
Project Management Article Transport Magazine dual language rev6
 
Angka indeks statistika
Angka indeks statistikaAngka indeks statistika
Angka indeks statistika
 

Similar to Ds 6

sorting algorithm graphical method
sorting algorithm graphical method sorting algorithm graphical method
sorting algorithm graphical method
Shantanu Mishra
 
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
 
Comparative Performance Analysis & Complexity of Different Sorting Algorithm
Comparative Performance Analysis & Complexity of Different Sorting AlgorithmComparative Performance Analysis & Complexity of Different Sorting Algorithm
Comparative Performance Analysis & Complexity of Different Sorting Algorithm
paperpublications3
 
14-sorting.ppt
14-sorting.ppt14-sorting.ppt
14-sorting.ppt
RenalthaPujaBagaskar
 
14-sorting (3).ppt
14-sorting (3).ppt14-sorting (3).ppt
14-sorting (3).ppt
yasser3omr
 
14-sorting.ppt
14-sorting.ppt14-sorting.ppt
14-sorting.ppt
SushantRaj25
 
14-sorting.ppt
14-sorting.ppt14-sorting.ppt
14-sorting.ppt
KamalAlbashiri
 
Unit III Version I.pptx
Unit III Version I.pptxUnit III Version I.pptx
Unit III Version I.pptx
ssuserd602fd
 
Sorting and Searching - Data Structure - Notes
Sorting and Searching - Data Structure - NotesSorting and Searching - Data Structure - Notes
Sorting and Searching - Data Structure - Notes
Omprakash Chauhan
 
Sorting
SortingSorting
Sorting
Samsil Arefin
 
sorting.pptx
sorting.pptxsorting.pptx
sorting.pptx
DrRanjeetKumar51721
 
Bin Sorting And Bubble Sort By Luisito G. Trinidad
Bin Sorting And Bubble Sort By Luisito G. TrinidadBin Sorting And Bubble Sort By Luisito G. Trinidad
Bin Sorting And Bubble Sort By Luisito G. Trinidad
LUISITO TRINIDAD
 
Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdf
AkashSingh625550
 
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
 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdf
Shiwani Gupta
 
Sorting
SortingSorting
Sorting
Shaista Qadir
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
BG Java EE Course
 
UNIT I_PSPP - Illustrative Problems (1).pptx
UNIT I_PSPP - Illustrative Problems (1).pptxUNIT I_PSPP - Illustrative Problems (1).pptx
UNIT I_PSPP - Illustrative Problems (1).pptx
RSathyaPriyaCSEKIOT
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
pppepito86
 
Searching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structuresSearching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structures
PRIANKA R
 

Similar to Ds 6 (20)

sorting algorithm graphical method
sorting algorithm graphical method sorting algorithm graphical method
sorting algorithm graphical method
 
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...
 
Comparative Performance Analysis & Complexity of Different Sorting Algorithm
Comparative Performance Analysis & Complexity of Different Sorting AlgorithmComparative Performance Analysis & Complexity of Different Sorting Algorithm
Comparative Performance Analysis & Complexity of Different Sorting Algorithm
 
14-sorting.ppt
14-sorting.ppt14-sorting.ppt
14-sorting.ppt
 
14-sorting (3).ppt
14-sorting (3).ppt14-sorting (3).ppt
14-sorting (3).ppt
 
14-sorting.ppt
14-sorting.ppt14-sorting.ppt
14-sorting.ppt
 
14-sorting.ppt
14-sorting.ppt14-sorting.ppt
14-sorting.ppt
 
Unit III Version I.pptx
Unit III Version I.pptxUnit III Version I.pptx
Unit III Version I.pptx
 
Sorting and Searching - Data Structure - Notes
Sorting and Searching - Data Structure - NotesSorting and Searching - Data Structure - Notes
Sorting and Searching - Data Structure - Notes
 
Sorting
SortingSorting
Sorting
 
sorting.pptx
sorting.pptxsorting.pptx
sorting.pptx
 
Bin Sorting And Bubble Sort By Luisito G. Trinidad
Bin Sorting And Bubble Sort By Luisito G. TrinidadBin Sorting And Bubble Sort By Luisito G. Trinidad
Bin Sorting And Bubble Sort By Luisito G. Trinidad
 
Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdf
 
Data Structures- Part4 basic sorting algorithms
Data Structures- Part4 basic sorting algorithmsData Structures- Part4 basic sorting algorithms
Data Structures- Part4 basic sorting algorithms
 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdf
 
Sorting
SortingSorting
Sorting
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
UNIT I_PSPP - Illustrative Problems (1).pptx
UNIT I_PSPP - Illustrative Problems (1).pptxUNIT I_PSPP - Illustrative Problems (1).pptx
UNIT I_PSPP - Illustrative Problems (1).pptx
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
 
Searching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structuresSearching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structures
 

More from Niit Care

Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
Niit Care
 
Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
Niit Care
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
Niit Care
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
Niit Care
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
Niit Care
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
Niit Care
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
Niit Care
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
Niit Care
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
Niit Care
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
Niit Care
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
Niit Care
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
Niit Care
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
Niit Care
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
Niit Care
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
Niit Care
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
Niit Care
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
Niit Care
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
Niit Care
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
Niit Care
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
Niit Care
 

More from Niit Care (20)

Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 

Recently uploaded

Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Zilliz
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 

Recently uploaded (20)

Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 

Ds 6

  • 1. Introduction to Sorting Techniques Objectives In this lesson, you will learn to: State the different sorting techniques State the complexities in the different sorting algorithms Introduction to Sorting Techniques/Lesson 6/Slide 1 of 40 ©NIIT
  • 2. Introduction to Sorting Techniques Sorting Sorting and searching are fundamental operations performed on data Sorting refers to operation of arranging data in given order Searching refers to finding a location of given item Algorithm chosen depends on operation to be performed on data Introduction to Sorting Techniques/Lesson 6/Slide 2 of 40 ©NIIT
  • 3. Introduction to Sorting Techniques Sorting (Contd..) Some sorting algorithms in use are: Bubble sort Selection sort Insertion sort Merge sort Quick sort Introduction to Sorting Techniques/Lesson 6/Slide 3 of 40 ©NIIT
  • 4. Introduction to Sorting Techniques Bubble Sort Take a list of numbers consisting of n elements This algorithm requires to traverse the list n-1 times Traversing the entire list once is called a pass For a list of n numbers there will be n-1 passes Introduction to Sorting Techniques/Lesson 6/Slide 4 of 40 ©NIIT
  • 5. Introduction to Sorting Techniques Bubble Sort (Contd..) Step 1: Compare first two elements and arrange them Compare second and third element and arrange them Compare fourth and fifth and arrange them Compare n-1 with nth element and arrange them Step 2: Repeat step 1 with one less comparison Introduction to Sorting Techniques/Lesson 6/Slide 5 of 40 ©NIIT
  • 6. Introduction to Sorting Techniques Bubble Sort (Contd..) Step 3: Repeat step 1 with two less comparison Step N: This step will have only one comparison Example: Sort 5, 2, 6, 7, 3 using bubble sort Introduction to Sorting Techniques/Lesson 6/Slide 6 of 40 ©NIIT
  • 7. Introduction to Sorting Techniques Bubble Sort (Contd..) Pass 1: Compare first and second element. If X1 X2 interchange as 2, 5, 6, 7, 3 Compare X2 with X3. If X2 X3 interchange else the list remains as it is Compare X3 with X4. Since X3 X4, list remains the same Introduction to Sorting Techniques/Lesson 6/Slide 7 of 40 ©NIIT
  • 8. Introduction to Sorting Techniques Bubble Sort (Contd..) Compare X4 with X5. Since X4 X5 interchange happens 2, 5, 6, 3, 7 At the end of this pass, the largest number is placed at the last position. Let us see what happens for the remainder of passes Pass 2: 2 5 6 3 7 2 5 6 3 7 2 5 3 6 7 Introduction to Sorting Techniques/Lesson 6/Slide 8 of 40 ©NIIT
  • 9. Introduction to Sorting Techniques Bubble Sort (Contd.) Pass 3 : 2 5 3 6 7 2 3 5 6 7 Pass 4 : 2 3 5 6 7 All the elements are sorted after the fourth pass Introduction to Sorting Techniques/Lesson 6/Slide 9 of 40 ©NIIT
  • 10. Introduction to Sorting Techniques Problem Statement 6.D.1 Write a program to store 10 student marks. After implementing the bubble sorting, display the contents of sorted array. Introduction to Sorting Techniques/Lesson 6/Slide 10 of ©NIIT 40
  • 11. Introduction to Sorting Techniques Selection Sort The algorithm finds the smallest element and puts it in first position Then finds second smallest and puts in the second position This is done for n-1 times Introduction to Sorting Techniques/Lesson 6/Slide 11 of ©NIIT 40
  • 12. Introduction to Sorting Techniques Selection Sort (Contd..) Consider an array Num of n elements Step 1: Search for location of smallest element Interchange the contents with the first location in the array Step 2: Search for smallest element in sublist of n-1 elements Interchange with the contents of the second location Introduction to Sorting Techniques/Lesson 6/Slide 12 of ©NIIT 40
  • 13. Introduction to Sorting Techniques Selection Sort (Contd..) Step n: Search for the smaller between n-1 and n and interchange Take a variable MIN to contain the current smallest value A variable LOC to contain the location of the smallest value Traverse the list comparing minimum with other elements Introduction to Sorting Techniques/Lesson 6/Slide 13 of ©NIIT 40
  • 14. Introduction to Sorting Techniques Selection Sort (Contd..) If MIN = Num[i] then MIN=Num[i] else move to next location MIN will contain the smallest value after comparison with the last element LOC will contain the location of MIN Introduction to Sorting Techniques/Lesson 6/Slide 14 of ©NIIT 40
  • 15. Introduction to Sorting Techniques Selection Sort (Contd..) This procedure finds the smallest of the elements among NUM[I], NUM[I+1], . .. , NUM[N] MINIMUM(NUM,I,N,LOC) 1. Set MIN=NUM[I] and LOC = I 2. Repeat for J = I + 1, I + 2 , . . . , N If MIN NUM[J] then set MIN = NUM[J] and LOC = J 3. Return Introduction to Sorting Techniques/Lesson 6/Slide 15 of ©NIIT 40
  • 16. Introduction to Sorting Techniques Selection Sort (Contd..) Algorithm: This algorithm sorts an array with N elements. 4. Repeat steps 2 and 3 for I=1,2,3,..., N 5. Call MINIMUM(NUM,I,N, LOC) 6. [Interchange Num[I] with NUM[LOC]] Introduction to Sorting Techniques/Lesson 6/Slide 16 of ©NIIT 40
  • 17. Introduction to Sorting Techniques Selection Sort (Contd.) Set TEMP= NUM[I], NUM[I] = NUM[LOC] NUM[LOC]=TEMP. [loop of step 1 ends] 6. Exit Introduction to Sorting Techniques/Lesson 6/Slide 17 of ©NIIT 40
  • 18. Introduction to Sorting Techniques Selection Sort (Contd..) Pass Num[1] Num[2] Num[3] Num[4] Num[5] Num[6] I=1 LOC=5 35 57 30 76 3 10 I=2 LOC=6 3 57 30 76 35 10 I=3 LOC=3 3 10 30 76 35 57 I=4 LOC=5 3 10 30 76 35 57 I=5 LOC=6 3 10 30 35 76 57 Sorted 3 10 30 35 57 76 Introduction to Sorting Techniques/Lesson 6/Slide 18 of ©NIIT 40
  • 19. Introduction to Sorting Techniques Insertion Sort An element is put into its correct position with each iteration of the main loop, relative to the sub-array that has already been processed Inserts each element to its proper location Frequently used with small number of elements Introduction to Sorting Techniques/Lesson 6/Slide 19 of ©NIIT 40
  • 20. Introduction to Sorting Techniques Insertion Sort (Contd..) The following steps are performed Pass 1: Num[1] by itself is sorted Pass 2: Num[2] is inserted either before or after Num[1] , such that Num[1] and Num[2] are sorted Pass 3: Num[3] is inserted into its proper place, i.e. before Num[1], between Num[1] and Num[2], or after Num[2], such that Num[1], Num[2], Num[3] are sorted Introduction to Sorting Techniques/Lesson 6/Slide 20 of ©NIIT 40
  • 21. Introduction to Sorting Techniques Insertion Sort (Contd..) .... .... .... .... .... .... Pass N: Num[n] is inserted into its proper place such that Num[1], Num[2],... ,Num[n] is sorted Introduction to Sorting Techniques/Lesson 6/Slide 21 of ©NIIT 40
  • 22. Introduction to Sorting Techniques Insertion Sort (Contd..) Pass Num[1] Num[2] Num[3] Num[4] Num[5] Num[6] Num[6] K=1 -∞ 35 57 30 76 3 10 K=2 -∞ 35 57 30 76 3 10 K=3 -∞ 35 57 30 76 3 10 K=4 -∞ 30 35 57 76 3 10 K=5 -∞ 30 35 57 76 3 10 K=6 -∞ 3 30 35 57 76 10 Sorted -∞ 3 10 30 35 57 76 Introduction to Sorting Techniques/Lesson 6/Slide 22 of ©NIIT 40
  • 23. Introduction to Sorting Techniques Insertion Sort (Contd..) Algorithm: INSERTION (NUM,N) The algorithm sorts the array NUM with N elements 1. Set Num[0] = -∞ [ Initialize the sentinel element] 2. Repeat steps 3 to 5 for K=2,3,4,... , N 3. Set TEMP=Num[K] and PTR =K-1 Introduction to Sorting Techniques/Lesson 6/Slide 23 of ©NIIT 40
  • 24. Introduction to Sorting Techniques Insertion Sort (Contd..) 1. Do while TEMP Num[PTR] a. Set Num[PTR+1] = Num[PTR] b. Set PTR=PTR – 1 (end of loop) 1. Set Num[PTR+1]=TEMP (end of loop) 1. Return Introduction to Sorting Techniques/Lesson 6/Slide 24 of ©NIIT 40
  • 25. Introduction to Sorting Techniques Problem Statement 6.P.1 Write a function implementing insertion sorting. Introduction to Sorting Techniques/Lesson 6/Slide 25 of ©NIIT 40
  • 26. Introduction to Sorting Techniques Merge Sort Step 1: Split the list into sublists of equal size Step 2: Sort them separately Step 3: Merge them together Introduction to Sorting Techniques/Lesson 6/Slide 26 of ©NIIT 40
  • 27. Introduction to Sorting Techniques Merge Sort (Contd..) Example: Let us sort 53, 10,30,76,3,57,24 using merge sort Step 1: Chop them into pairs and sort them 53, 10 30, 76 3, 57 24 Step 2: Merge the pairs to obtain the following sorted sublists 10,53 30,76 3,57 24 Introduction to Sorting Techniques/Lesson 6/Slide 27 of ©NIIT 40
  • 28. Introduction to Sorting Techniques Merge Sort (Contd..) Step 3: Merge the sorted sublists to obtain a single sorted array 3, 10, 24, 30, 53, 57, 76 The original array is now sorted Introduction to Sorting Techniques/Lesson 6/Slide 28 of ©NIIT 40
  • 29. Introduction to Sorting Techniques Quick Sort We arrange the list in some logical order Algorithm is divide and conquer type Sorting is reduced to sorting two smaller subsets Reduction step finds the final position of one number Introduction to Sorting Techniques/Lesson 6/Slide 29 of ©NIIT 40
  • 30. Introduction to Sorting Techniques Quick Sort (Contd..) Step1: Take first element as key element Scan right to left for an element less than key element Interchange positions of the elements Step 2: Scan right to left for element greater than key element Interchange positions of the elements Introduction to Sorting Techniques/Lesson 6/Slide 30 of ©NIIT 40
  • 31. Introduction to Sorting Techniques Quick Sort (Contd..) Step 3: Continue step 1 and step 2 till ® all element in right are greater than key ® all element in left are less than key The key element will be placed in its correct position Repeat reduction step for each sub list with two or more elements Introduction to Sorting Techniques/Lesson 6/Slide 31 of ©NIIT 40
  • 32. Introduction to Sorting Techniques Quick Sort (Contd..) Example: 35 57 30 76 3 10 In this example we take the number 35 as the key STEP 1: 10 57 30 76 3 35 STEP 2: 10 35 30 76 3 57 STEP 3: 10 3 30 76 35 57 STEP 3: 10 3 30 35 76 57 35 is correctly placed in its final position Introduction to Sorting Techniques/Lesson 6/Slide 32 of ©NIIT 40
  • 33. Introduction to Sorting Techniques Problem Statement 6.D.2 Write a program to store 10 numbers in an array. After implementing quick sorting, display the contents of the sorted array. Introduction to Sorting Techniques/Lesson 6/Slide 33 of ©NIIT 40
  • 34. Introduction to Sorting Techniques Complexities For bubble sort The number of comparisons f(n) = (n-1) + (n-2) + (n-3) +...+ 2 + 1 = n(n-1) 2 = n2 + O(n) = O(n2) 2 Introduction to Sorting Techniques/Lesson 6/Slide 34 of ©NIIT 40
  • 35. Introduction to Sorting Techniques Complexities (Contd..) For quick sort Worst case (when the list is already sorted) f(n) = n + (n-1) + (n-2) +...+2 + 1 = n(n-1) = n2 + O(n) = O(n2) 2 2 Average case ® In kth level finds the location of 2K-1 elements f(n) = O(n log n) Introduction to Sorting Techniques/Lesson 6/Slide 35 of ©NIIT 40
  • 36. Introduction to Sorting Techniques Complexities (Contd..) For selection sort Number of comparisons depends on original order of elements There are n-1 comparisons in pass1 There are n-2 comparisons in pass 2 f(n) = (n-1) + (n-2) + (n-3) +...+ 2 + 1 = n(n-1) = n2 + O(n) = O(n2) 2 2 Introduction to Sorting Techniques/Lesson 6/Slide 36 of ©NIIT 40
  • 37. Introduction to Sorting Techniques Complexities (Contd..) For insertion sort Worst case occurs when the array is in the reverse order Inner loop executes maximum number K-1 of comparisons f(n) = 1+ 2 + . . . + (n-1) = n(n-1) = O(n2) 2 Introduction to Sorting Techniques/Lesson 6/Slide 37 of ©NIIT 40
  • 38. Introduction to Sorting Techniques Complexities (Contd..) Average case There will be approximately (K-1)/2 comparisons in the inner loop f(n) = 1+ 2+ 3+ . . .+ (n-1) = n(n-1) = O(n2) 2 2 2 2 4 Introduction to Sorting Techniques/Lesson 6/Slide 38 of ©NIIT 40
  • 39. Introduction to Sorting Techniques Summary In this lesson, you learned that: Different types of sorting are: Bubble sort Selection sort Insertion sort Merge sort Quick sort Introduction to Sorting Techniques/Lesson 6/Slide 39 of ©NIIT 40
  • 40. Introduction to Sorting Techniques Summary (Contd..) The time required to execute bubble sort algorithm is proportional to n2, where n is the number of inputs The number of comparisons in a selection sort is independent of the original order of the elements The insertion sort is a very slow algorithm when the number of elements in the array is very large The Quick sort algorithm has a worst case running time of order n2/2 Introduction to Sorting Techniques/Lesson 6/Slide 40 of ©NIIT 40

Editor's Notes

  1. Lower Bound and Upper Bound to denote the first element number and the last element number respectively
  2. Lower Bound and Upper Bound to denote the first element number and the last element number respectively