SlideShare a Scribd company logo
Simple Sorting Algorithms
2
Bubble sort
 Compare each element (except the last one) with its
neighbor to the right
 If they are out of order, swap them
 This puts the largest element at the very end
 The last element is now in the correct and final place
 Compare each element (except the last two) with its
neighbor to the right
 If they are out of order, swap them
 This puts the second largest element next to last
 The last two elements are now in their correct and final places
 Compare each element (except the last three) with its
neighbor to the right
 Continue as above until you have no unsorted elements on the left
3
Example of bubble sort
7 2 8 5 4
2 7 8 5 4
2 7 8 5 4
2 7 5 8 4
2 7 5 4 8
2 7 5 4 8
2 5 7 4 8
2 5 4 7 8
2 7 5 4 8
2 5 4 7 8
2 4 5 7 8
2 5 4 7 8
2 4 5 7 8
2 4 5 7 8
(done)
4
Code for bubble sort
 public static void bubbleSort(int[] a) {
int outer, inner;
for (outer = a.length - 1; outer > 0; outer--) { // counting down
for (inner = 0; inner < outer; inner++) { // bubbling up
if (a[inner] > a[inner + 1]) { // if out of order...
int temp = a[inner]; // ...then swap
a[inner] = a[inner + 1];
a[inner + 1] = temp;
}
}
}
}
5
Analysis of bubble sort
 for (outer = a.length - 1; outer > 0; outer--) {
for (inner = 0; inner < outer; inner++) {
if (a[inner] > a[inner + 1]) {
// code for swap omitted
} } }
 Let n = a.length = size of the array
 The outer loop is executed n-1 times (call it n, that’s close enough)
 Each time the outer loop is executed, the inner loop is executed
 Inner loop executes n-1 times at first, linearly dropping to just once
 On average, inner loop executes about n/2 times for each execution
of the outer loop
 In the inner loop, the comparison is always done (constant time), the
swap might be done (also constant time)
 Result is n * n/2 * k, that is, O(n2/2 + k) = O(n2
)
6
Loop invariants
 You run a loop in order to change things
 Oddly enough, what is usually most important in understanding a
loop is finding an invariant: that is, a condition that doesn’t
change
 In bubble sort, we put the largest elements at the end, and once
we put them there, we don’t move them again
 The variable outer starts at the last index in the array and decreases to 0
 Our invariant is: Every element to the right of outer is in the correct place
 That is, for all j > outer, if i < j, then a[i] <= a[j]
 When this is combined with the loop exit test, outer == 0, we know that
all elements of the array are in the correct place
7
Selection sort
 Given an array of length n,
 Search elements 0 through n-1 and select the smallest

Swap it with the element in location 0
 Search elements 1 through n-1 and select the smallest

Swap it with the element in location 1
 Search elements 2 through n-1 and select the smallest

Swap it with the element in location 2
 Search elements 3 through n-1 and select the smallest

Swap it with the element in location 3
 Continue in this fashion until there’s nothing left to search
8
Example and analysis of selection sort
 The selection sort might swap an
array element with itself--this is
harmless, and not worth checking for
 Analysis:
 The outer loop executes n-1 times
 The inner loop executes about n/2
times on average (from n to 2 times)
 Work done in the inner loop is constant
(swap two array elements)
 Time required is roughly (n-1)*(n/2)
 You should recognize this as O(n2
)
7 2 8 5 4
2 7 8 5 4
2 4 8 5 7
2 4 5 8 7
2 4 5 7 8
9
Code for selection sort
public static void selectionSort(int[] a) {
int outer, inner, min;
for (outer = 0; outer < a.length - 1; outer++) {
min = outer;
for (inner = outer + 1; inner < a.length; inner++) {
if (a[inner] < a[min]) {
min = inner;
}
// Invariant: for all i, if outer <= i <= inner, then a[min] <= a[i]
}
// a[min] is least among a[outer]..a[a.length - 1]
int temp = a[outer];
a[outer] = a[min];
a[min] = temp;
// Invariant: for all i <= outer, if i < j then a[i] <= a[j]
}
}
10
Invariants for selection sort
 For the inner loop:
 This loop searches through the array, incrementing inner from its initial
value of outer+1 up to a.length-1
 As the loop proceeds, min is set to the index of the smallest number
found so far
 Our invariant is:
for all i such that outer <= i <= inner, a[min] <= a[i]
 For the outer (enclosing) loop:
 The loop counts up from outer = 0
 Each time through the loop, the minimum remaining value is put in
a[outer]
 Our invariant is:
for all i <= outer, if i < j then a[i] <= a[j]
11
Insertion sort
 The outer loop of insertion sort is:
for (outer = 1; outer < a.length; outer++) {...}
 The invariant is that all the elements to the left of outer
are sorted with respect to one another
 For all i < outer, j < outer, if i < j then a[i] <= a[j]
 This does not mean they are all in their final correct place; the
remaining array elements may need to be inserted
 When we increase outer, a[outer-1] becomes to its left; we must
keep the invariant true by inserting a[outer-1] into its proper
place
 This means:

Finding the element’s proper place

Making room for the inserted element (by shifting over other
elements)

Inserting the element
12
One step of insertion sort
3 4 7 12 14 14 20 21 33 38 10 55 9 23 28 16
sorted next to be inserted
3 4 7 55 9 23 28 16
10
temp
3833212014141210
sorted
less than 10
13
Analysis of insertion sort
 We run once through the outer loop, inserting each of n
elements; this is a factor of n
 On average, there are n/2 elements already sorted
 The inner loop looks at (and moves) half of these
 This gives a second factor of n/4
 Hence, the time required for an insertion sort of an array
of n elements is proportional to n2
/4
 Discarding constants, we find that insertion sort is O(n2
)
Merge sort
30 24 7 12 14 4 20 21 33 38 10 55 9 23 28 16
33 38 10 55 9 23 28 1630 24 7 12 14 4 20 21
Split the array into
two or more parts
Sort each part individually
4 7 12 14 20 21 24 30 9 10 16 23 28 33 38 55
Merge
4 7 9 10 12 14 16 20 21 23 24 28 30 33 38 55
Why merge sort?
 Merge sort isn’t an “in place” sort—it requires extra
storage
 However, it doesn’t require this storage “all at once”
 This means you can use merge sort to sort something
that doesn’t fit in memory—say, 300 million census
records—then much of the data must be kept on backup
media, such as a hard drive
 Merge sort is a good way to do this
15
Using merge sort for large data sets
 Very roughly, here’s how to sort large amounts of data:
 Repeat:

Read in as much data as fits in memory

Sort it, using a fast sorting algorithm (quicksort may be a good choice)

Write out the sorted data to a new file
 After all the data has been written into smaller, individually
sorted files:

Read in the initial portion of each sorted file into individual arrays

Start merging the arrays

Whenever an array becomes empty, read in more data from its file

Every so often, write the destination array to the (one) final output file
 When you are done, you will have one (large) sorted
file
16
17
Summary
 Most of the sorting techniques we have discussed are O(n2
)
 As we will see later, we can do much better than this with somewhat
more complicated sorting algorithms
 Within O(n2
),
 Bubble sort is very slow, and should probably never be used for anything
 Selection sort is intermediate in speed
 Insertion sort is usually faster than selection sort—in fact, for small arrays
(say, 10 or 20 elements), insertion sort is faster than more complicated
sorting algorithms

Merge sort, if done in memory, is O(n log n)
 Selection sort and insertion sort are “good enough” for small arrays
 Merge sort is good for sorting data that doesn’t fit in main memory
18
The End

More Related Content

What's hot

Fourier transforms of discrete signals (DSP) 5
Fourier transforms of discrete signals (DSP) 5Fourier transforms of discrete signals (DSP) 5
Fourier transforms of discrete signals (DSP) 5
HIMANSHU DIWAKAR
 
The theory of concurrent programming for a seasoned programmer
The theory of concurrent programming for a seasoned programmerThe theory of concurrent programming for a seasoned programmer
The theory of concurrent programming for a seasoned programmerRoman Elizarov
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
keval_thummar
 
Fundamental concurrent programming
Fundamental concurrent programmingFundamental concurrent programming
Fundamental concurrent programming
Dimas Prawira
 
Determination of DTFT | Computer Science
Determination of DTFT | Computer ScienceDetermination of DTFT | Computer Science
Determination of DTFT | Computer Science
Transweb Global Inc
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
Alex Miller
 
DSP_FOEHU - MATLAB 03 - The z-Transform
DSP_FOEHU - MATLAB 03 - The z-TransformDSP_FOEHU - MATLAB 03 - The z-Transform
DSP_FOEHU - MATLAB 03 - The z-Transform
Amr E. Mohamed
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingzukun
 
Thread
ThreadThread
Thread
Juhi Kumari
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
feng lee
 
3.9 external sorting
3.9 external sorting3.9 external sorting
3.9 external sorting
Krish_ver2
 
Python multithreaded programming
Python   multithreaded programmingPython   multithreaded programming
Python multithreaded programming
Learnbay Datascience
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
Gaurav Aggarwal
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37myrajendra
 
A Survey of Adaptive QuickSort Algorithms
A Survey of Adaptive QuickSort AlgorithmsA Survey of Adaptive QuickSort Algorithms
A Survey of Adaptive QuickSort Algorithms
CSCJournals
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
Lec3
Lec3Lec3
Lec3
bsnl007
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
Jayant Dalvi
 
Threads in java
Threads in javaThreads in java
Threads in java
mukesh singh
 
Lec5
Lec5Lec5
Lec5
bsnl007
 

What's hot (20)

Fourier transforms of discrete signals (DSP) 5
Fourier transforms of discrete signals (DSP) 5Fourier transforms of discrete signals (DSP) 5
Fourier transforms of discrete signals (DSP) 5
 
The theory of concurrent programming for a seasoned programmer
The theory of concurrent programming for a seasoned programmerThe theory of concurrent programming for a seasoned programmer
The theory of concurrent programming for a seasoned programmer
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
 
Fundamental concurrent programming
Fundamental concurrent programmingFundamental concurrent programming
Fundamental concurrent programming
 
Determination of DTFT | Computer Science
Determination of DTFT | Computer ScienceDetermination of DTFT | Computer Science
Determination of DTFT | Computer Science
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
DSP_FOEHU - MATLAB 03 - The z-Transform
DSP_FOEHU - MATLAB 03 - The z-TransformDSP_FOEHU - MATLAB 03 - The z-Transform
DSP_FOEHU - MATLAB 03 - The z-Transform
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sorting
 
Thread
ThreadThread
Thread
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
3.9 external sorting
3.9 external sorting3.9 external sorting
3.9 external sorting
 
Python multithreaded programming
Python   multithreaded programmingPython   multithreaded programming
Python multithreaded programming
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
A Survey of Adaptive QuickSort Algorithms
A Survey of Adaptive QuickSort AlgorithmsA Survey of Adaptive QuickSort Algorithms
A Survey of Adaptive QuickSort Algorithms
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
 
Lec3
Lec3Lec3
Lec3
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Lec5
Lec5Lec5
Lec5
 

Viewers also liked

History of Creationism, Parts II & III
History of Creationism, Parts II & IIIHistory of Creationism, Parts II & III
History of Creationism, Parts II & IIIJohn Lynch
 
A history of science (volume 1)
A history of science (volume 1) A history of science (volume 1)
A history of science (volume 1) Dipoceanov Esrever
 
Tri Merge Sorting Algorithm
Tri Merge Sorting AlgorithmTri Merge Sorting Algorithm
Tri Merge Sorting Algorithm
Ashim Sikder
 
Why Ben Stein Is Wrong About History & Science
Why Ben Stein Is Wrong About History & ScienceWhy Ben Stein Is Wrong About History & Science
Why Ben Stein Is Wrong About History & Science
John Lynch
 
Introduction to Information Technology ch 01_b
Introduction to Information Technology ch 01_bIntroduction to Information Technology ch 01_b
Introduction to Information Technology ch 01_b
Shahi Raz Akhtar
 
Was There A Darwinian Revolution
Was There A Darwinian RevolutionWas There A Darwinian Revolution
Was There A Darwinian Revolution
John Lynch
 
Google Algorithm Change History - 2k14-2k16.
Google Algorithm Change History - 2k14-2k16.Google Algorithm Change History - 2k14-2k16.
Google Algorithm Change History - 2k14-2k16.
Saba SEO
 
How We Got Where We Are: 40 Years of Planning...
How We Got Where We Are: 40 Years of Planning...How We Got Where We Are: 40 Years of Planning...
How We Got Where We Are: 40 Years of Planning...
American Astronautical Society
 
History of Google Local from 2004-2011
History of Google Local from 2004-2011 History of Google Local from 2004-2011
History of Google Local from 2004-2011
Mike Blumenthal
 
Introduction to "Origins, Evolution & Creation"
Introduction to "Origins, Evolution & Creation"Introduction to "Origins, Evolution & Creation"
Introduction to "Origins, Evolution & Creation"John Lynch
 
Ancient Ideas of Creation & Evolution
Ancient Ideas of Creation & EvolutionAncient Ideas of Creation & Evolution
Ancient Ideas of Creation & EvolutionJohn Lynch
 
Dc parent 14 2
Dc parent 14 2Dc parent 14 2
Dc parent 14 2mtaft
 
Chapter one
Chapter oneChapter one
Chapter one
mihiretu kassaye
 
Introduction to Information Technology ch 02_a
Introduction to Information Technology ch 02_aIntroduction to Information Technology ch 02_a
Introduction to Information Technology ch 02_a
Shahi Raz Akhtar
 
sPen Data Management
sPen Data ManagementsPen Data Management
sPen Data Management
Uladzimir Slabin
 
One Long Argument
One Long ArgumentOne Long Argument
One Long ArgumentJohn Lynch
 
National Air And Space Museum Washington DC
National Air And Space Museum Washington DCNational Air And Space Museum Washington DC
National Air And Space Museum Washington DC
Shivakumar Patil
 

Viewers also liked (20)

History of Creationism, Parts II & III
History of Creationism, Parts II & IIIHistory of Creationism, Parts II & III
History of Creationism, Parts II & III
 
Chap04alg
Chap04algChap04alg
Chap04alg
 
A history of science (volume 1)
A history of science (volume 1) A history of science (volume 1)
A history of science (volume 1)
 
Tri Merge Sorting Algorithm
Tri Merge Sorting AlgorithmTri Merge Sorting Algorithm
Tri Merge Sorting Algorithm
 
Why Ben Stein Is Wrong About History & Science
Why Ben Stein Is Wrong About History & ScienceWhy Ben Stein Is Wrong About History & Science
Why Ben Stein Is Wrong About History & Science
 
Introduction to Information Technology ch 01_b
Introduction to Information Technology ch 01_bIntroduction to Information Technology ch 01_b
Introduction to Information Technology ch 01_b
 
Was There A Darwinian Revolution
Was There A Darwinian RevolutionWas There A Darwinian Revolution
Was There A Darwinian Revolution
 
Google Algorithm Change History - 2k14-2k16.
Google Algorithm Change History - 2k14-2k16.Google Algorithm Change History - 2k14-2k16.
Google Algorithm Change History - 2k14-2k16.
 
How We Got Where We Are: 40 Years of Planning...
How We Got Where We Are: 40 Years of Planning...How We Got Where We Are: 40 Years of Planning...
How We Got Where We Are: 40 Years of Planning...
 
History of Google Local from 2004-2011
History of Google Local from 2004-2011 History of Google Local from 2004-2011
History of Google Local from 2004-2011
 
Introduction to "Origins, Evolution & Creation"
Introduction to "Origins, Evolution & Creation"Introduction to "Origins, Evolution & Creation"
Introduction to "Origins, Evolution & Creation"
 
Ancient Ideas of Creation & Evolution
Ancient Ideas of Creation & EvolutionAncient Ideas of Creation & Evolution
Ancient Ideas of Creation & Evolution
 
Ds 4
Ds 4Ds 4
Ds 4
 
Dc parent 14 2
Dc parent 14 2Dc parent 14 2
Dc parent 14 2
 
Chapter one
Chapter oneChapter one
Chapter one
 
Introduction to Information Technology ch 02_a
Introduction to Information Technology ch 02_aIntroduction to Information Technology ch 02_a
Introduction to Information Technology ch 02_a
 
sPen Data Management
sPen Data ManagementsPen Data Management
sPen Data Management
 
One Long Argument
One Long ArgumentOne Long Argument
One Long Argument
 
National Air And Space Museum Washington DC
National Air And Space Museum Washington DCNational Air And Space Museum Washington DC
National Air And Space Museum Washington DC
 
Google
GoogleGoogle
Google
 

Similar to simple-sorting algorithms

Sorting Algorithms.
Sorting Algorithms.Sorting Algorithms.
Sorting Algorithms.
Saket Kumar
 
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
 
Selection sort
Selection sortSelection sort
Selection sortasra khan
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & AlgorithumsAin-ul-Moiz Khawaja
 
Chapter-2.pptx
Chapter-2.pptxChapter-2.pptx
Chapter-2.pptx
selemonGamo
 
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisAnalysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Radhika Talaviya
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
CHANDAN KUMAR
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
Eduardo Bergavera
 
Basic Sorting algorithms csharp
Basic Sorting algorithms csharpBasic Sorting algorithms csharp
Basic Sorting algorithms csharp
Micheal Ogundero
 
Selection sort lab mannual
Selection sort lab mannualSelection sort lab mannual
Selection sort lab mannual
maamir farooq
 
lecture-k-sorting.ppt
lecture-k-sorting.pptlecture-k-sorting.ppt
lecture-k-sorting.ppt
SushantRaj25
 
3.ppt
3.ppt3.ppt
Module 2_ Divide and Conquer Approach.pptx
Module 2_ Divide and Conquer Approach.pptxModule 2_ Divide and Conquer Approach.pptx
Module 2_ Divide and Conquer Approach.pptx
nikshaikh786
 
sorting-160810203705.pptx
sorting-160810203705.pptxsorting-160810203705.pptx
sorting-160810203705.pptx
VarchasvaTiwari2
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
Dr.Umadevi V
 
(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sortingFadhil Ismail
 
Chapter 4 ds
Chapter 4 dsChapter 4 ds
Chapter 4 ds
Hanif Durad
 
Time and Space Complexity Analysis.pptx
Time and Space Complexity Analysis.pptxTime and Space Complexity Analysis.pptx
Time and Space Complexity Analysis.pptx
dudelover
 

Similar to simple-sorting algorithms (20)

Sorting Algorithms.
Sorting Algorithms.Sorting Algorithms.
Sorting 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
 
Selection sort
Selection sortSelection sort
Selection sort
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & Algorithums
 
Chapter-2.pptx
Chapter-2.pptxChapter-2.pptx
Chapter-2.pptx
 
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisAnalysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysis
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 
Basic Sorting algorithms csharp
Basic Sorting algorithms csharpBasic Sorting algorithms csharp
Basic Sorting algorithms csharp
 
Selection sort lab mannual
Selection sort lab mannualSelection sort lab mannual
Selection sort lab mannual
 
lecture-k-sorting.ppt
lecture-k-sorting.pptlecture-k-sorting.ppt
lecture-k-sorting.ppt
 
3.ppt
3.ppt3.ppt
3.ppt
 
Module 2_ Divide and Conquer Approach.pptx
Module 2_ Divide and Conquer Approach.pptxModule 2_ Divide and Conquer Approach.pptx
Module 2_ Divide and Conquer Approach.pptx
 
Sorting
SortingSorting
Sorting
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
sorting-160810203705.pptx
sorting-160810203705.pptxsorting-160810203705.pptx
sorting-160810203705.pptx
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
 
(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting
 
Chapter 4 ds
Chapter 4 dsChapter 4 ds
Chapter 4 ds
 
Time and Space Complexity Analysis.pptx
Time and Space Complexity Analysis.pptxTime and Space Complexity Analysis.pptx
Time and Space Complexity Analysis.pptx
 

Recently uploaded

Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
ssuser36d3051
 
AIR POLLUTION lecture EnE203 updated.pdf
AIR POLLUTION lecture EnE203 updated.pdfAIR POLLUTION lecture EnE203 updated.pdf
AIR POLLUTION lecture EnE203 updated.pdf
RicletoEspinosa1
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Online aptitude test management system project report.pdf
Online aptitude test management system project report.pdfOnline aptitude test management system project report.pdf
Online aptitude test management system project report.pdf
Kamal Acharya
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
yokeleetan1
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
MIGUELANGEL966976
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
Rahul
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
Mukeshwaran Balu
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 

Recently uploaded (20)

Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
 
AIR POLLUTION lecture EnE203 updated.pdf
AIR POLLUTION lecture EnE203 updated.pdfAIR POLLUTION lecture EnE203 updated.pdf
AIR POLLUTION lecture EnE203 updated.pdf
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Online aptitude test management system project report.pdf
Online aptitude test management system project report.pdfOnline aptitude test management system project report.pdf
Online aptitude test management system project report.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 

simple-sorting algorithms

  • 2. 2 Bubble sort  Compare each element (except the last one) with its neighbor to the right  If they are out of order, swap them  This puts the largest element at the very end  The last element is now in the correct and final place  Compare each element (except the last two) with its neighbor to the right  If they are out of order, swap them  This puts the second largest element next to last  The last two elements are now in their correct and final places  Compare each element (except the last three) with its neighbor to the right  Continue as above until you have no unsorted elements on the left
  • 3. 3 Example of bubble sort 7 2 8 5 4 2 7 8 5 4 2 7 8 5 4 2 7 5 8 4 2 7 5 4 8 2 7 5 4 8 2 5 7 4 8 2 5 4 7 8 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8 2 5 4 7 8 2 4 5 7 8 2 4 5 7 8 (done)
  • 4. 4 Code for bubble sort  public static void bubbleSort(int[] a) { int outer, inner; for (outer = a.length - 1; outer > 0; outer--) { // counting down for (inner = 0; inner < outer; inner++) { // bubbling up if (a[inner] > a[inner + 1]) { // if out of order... int temp = a[inner]; // ...then swap a[inner] = a[inner + 1]; a[inner + 1] = temp; } } } }
  • 5. 5 Analysis of bubble sort  for (outer = a.length - 1; outer > 0; outer--) { for (inner = 0; inner < outer; inner++) { if (a[inner] > a[inner + 1]) { // code for swap omitted } } }  Let n = a.length = size of the array  The outer loop is executed n-1 times (call it n, that’s close enough)  Each time the outer loop is executed, the inner loop is executed  Inner loop executes n-1 times at first, linearly dropping to just once  On average, inner loop executes about n/2 times for each execution of the outer loop  In the inner loop, the comparison is always done (constant time), the swap might be done (also constant time)  Result is n * n/2 * k, that is, O(n2/2 + k) = O(n2 )
  • 6. 6 Loop invariants  You run a loop in order to change things  Oddly enough, what is usually most important in understanding a loop is finding an invariant: that is, a condition that doesn’t change  In bubble sort, we put the largest elements at the end, and once we put them there, we don’t move them again  The variable outer starts at the last index in the array and decreases to 0  Our invariant is: Every element to the right of outer is in the correct place  That is, for all j > outer, if i < j, then a[i] <= a[j]  When this is combined with the loop exit test, outer == 0, we know that all elements of the array are in the correct place
  • 7. 7 Selection sort  Given an array of length n,  Search elements 0 through n-1 and select the smallest  Swap it with the element in location 0  Search elements 1 through n-1 and select the smallest  Swap it with the element in location 1  Search elements 2 through n-1 and select the smallest  Swap it with the element in location 2  Search elements 3 through n-1 and select the smallest  Swap it with the element in location 3  Continue in this fashion until there’s nothing left to search
  • 8. 8 Example and analysis of selection sort  The selection sort might swap an array element with itself--this is harmless, and not worth checking for  Analysis:  The outer loop executes n-1 times  The inner loop executes about n/2 times on average (from n to 2 times)  Work done in the inner loop is constant (swap two array elements)  Time required is roughly (n-1)*(n/2)  You should recognize this as O(n2 ) 7 2 8 5 4 2 7 8 5 4 2 4 8 5 7 2 4 5 8 7 2 4 5 7 8
  • 9. 9 Code for selection sort public static void selectionSort(int[] a) { int outer, inner, min; for (outer = 0; outer < a.length - 1; outer++) { min = outer; for (inner = outer + 1; inner < a.length; inner++) { if (a[inner] < a[min]) { min = inner; } // Invariant: for all i, if outer <= i <= inner, then a[min] <= a[i] } // a[min] is least among a[outer]..a[a.length - 1] int temp = a[outer]; a[outer] = a[min]; a[min] = temp; // Invariant: for all i <= outer, if i < j then a[i] <= a[j] } }
  • 10. 10 Invariants for selection sort  For the inner loop:  This loop searches through the array, incrementing inner from its initial value of outer+1 up to a.length-1  As the loop proceeds, min is set to the index of the smallest number found so far  Our invariant is: for all i such that outer <= i <= inner, a[min] <= a[i]  For the outer (enclosing) loop:  The loop counts up from outer = 0  Each time through the loop, the minimum remaining value is put in a[outer]  Our invariant is: for all i <= outer, if i < j then a[i] <= a[j]
  • 11. 11 Insertion sort  The outer loop of insertion sort is: for (outer = 1; outer < a.length; outer++) {...}  The invariant is that all the elements to the left of outer are sorted with respect to one another  For all i < outer, j < outer, if i < j then a[i] <= a[j]  This does not mean they are all in their final correct place; the remaining array elements may need to be inserted  When we increase outer, a[outer-1] becomes to its left; we must keep the invariant true by inserting a[outer-1] into its proper place  This means:  Finding the element’s proper place  Making room for the inserted element (by shifting over other elements)  Inserting the element
  • 12. 12 One step of insertion sort 3 4 7 12 14 14 20 21 33 38 10 55 9 23 28 16 sorted next to be inserted 3 4 7 55 9 23 28 16 10 temp 3833212014141210 sorted less than 10
  • 13. 13 Analysis of insertion sort  We run once through the outer loop, inserting each of n elements; this is a factor of n  On average, there are n/2 elements already sorted  The inner loop looks at (and moves) half of these  This gives a second factor of n/4  Hence, the time required for an insertion sort of an array of n elements is proportional to n2 /4  Discarding constants, we find that insertion sort is O(n2 )
  • 14. Merge sort 30 24 7 12 14 4 20 21 33 38 10 55 9 23 28 16 33 38 10 55 9 23 28 1630 24 7 12 14 4 20 21 Split the array into two or more parts Sort each part individually 4 7 12 14 20 21 24 30 9 10 16 23 28 33 38 55 Merge 4 7 9 10 12 14 16 20 21 23 24 28 30 33 38 55
  • 15. Why merge sort?  Merge sort isn’t an “in place” sort—it requires extra storage  However, it doesn’t require this storage “all at once”  This means you can use merge sort to sort something that doesn’t fit in memory—say, 300 million census records—then much of the data must be kept on backup media, such as a hard drive  Merge sort is a good way to do this 15
  • 16. Using merge sort for large data sets  Very roughly, here’s how to sort large amounts of data:  Repeat:  Read in as much data as fits in memory  Sort it, using a fast sorting algorithm (quicksort may be a good choice)  Write out the sorted data to a new file  After all the data has been written into smaller, individually sorted files:  Read in the initial portion of each sorted file into individual arrays  Start merging the arrays  Whenever an array becomes empty, read in more data from its file  Every so often, write the destination array to the (one) final output file  When you are done, you will have one (large) sorted file 16
  • 17. 17 Summary  Most of the sorting techniques we have discussed are O(n2 )  As we will see later, we can do much better than this with somewhat more complicated sorting algorithms  Within O(n2 ),  Bubble sort is very slow, and should probably never be used for anything  Selection sort is intermediate in speed  Insertion sort is usually faster than selection sort—in fact, for small arrays (say, 10 or 20 elements), insertion sort is faster than more complicated sorting algorithms  Merge sort, if done in memory, is O(n log n)  Selection sort and insertion sort are “good enough” for small arrays  Merge sort is good for sorting data that doesn’t fit in main memory