SlideShare a Scribd company logo
Bubble Sort
 Compares adjacent array elements
– Exchanges their values if they are out of order
 Smaller values bubble up to the top of the array
– Larger values sink to the bottom
Bubble Sort (cont.)
 Example:
512354277 101
0 1 2 3 4 5
Swap42 77
Bubble Sort (cont.)
 Example:
512357742 101Swap35 77
0 1 2 3 4 5
Bubble Sort (cont.)
 Example:
512773542 101Swap12 77
0 1 2 3 4 5
Bubble Sort (cont.)
 Example:
577123542 101
No need to swap
0 1 2 3 4 5
Bubble Sort (cont.)
 Example:
577123542 101 Swap5 101
0 1 2 3 4 5
Bubble Sort (cont.)
 Example:
77123542 5 101
Largest value correctly placed
0 1 2 3 4 5
Bubble Sort (cont.)
• Notice that only the largest value is correctly
placed
• All other values are still out of order
• So we need to repeat this process
77123542 5 101
Largest value correctly placed
0 1 2 3 4 5
Bubble Sort (cont.)
Repeat “Bubble Up” How Many Times?
 If we have N elements…
 And if each time we bubble an element, we place it in its correct location…
 Then we repeat the “bubble up” process N – 1 times.
 This guarantees we’ll correctly place all N elements.
Bubble Sort (cont.)
77123542 5
0 1 2 3 4 5
101
5421235 77
0 1 2 3 4 5
101
4253512 77
0 1 2 3 4 5
101
4235512 77
0 1 2 3 4 5
101
4235125 77
0 1 2 3 4 5
101
N-1
Bubble Sort (cont.)
 What if the array was already sorted?
 What if only a few elements were out of place and after a couple of “bubble ups,”
the array was sorted?
 We want to be able to detect this and “stop early”!
Bubble Sort (cont.)
Using a Boolean “Flag”
 We can use a boolean variable to determine if any swapping occurred during the
“bubble up.”
 If no swapping occurred, then we know that the collection is already sorted!
 This boolean “flag” needs to be reset after each “bubble up.”
public static void BubbleSort( int [ ] num )
{
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag )
{
flag= false; //set flag to false awaiting a possible swap
for( j=0; j > num.length -1; j++ )
if ( num[ j ] > num[j+1] ) // change to > for ascending sort
{
temp = num[ j ]; //swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
Bubble Sort (cont.)
 Excellent performance in some cases
– But very poor performance in others!
 Works best when array is nearly sorted to begin with
 Worst case number of comparisons: n2
 Worst case number of exchanges: n2
 Best case occurs when the array is already sorted:
– n comparisons
– 0 exchanges

More Related Content

Similar to 8 elementary sorts-bubble

MYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptx
MYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptxMYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptx
MYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptx
ArjayBalberan1
 
Bubble sort
Bubble sortBubble sort
Bubble sort
Manek Ar
 
Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.
NikhilSoni177492
 
cs1311lecture16wdl.ppt
cs1311lecture16wdl.pptcs1311lecture16wdl.ppt
cs1311lecture16wdl.ppt
RameshKumarYadav29
 
Bubble Sort Python
Bubble Sort PythonBubble Sort Python
Bubble Sort Python
ValneyFilho1
 
Bubble Sort.ppt
Bubble Sort.pptBubble Sort.ppt
Bubble Sort.ppt
MuhammadSheraz836877
 
Bubble sort/ Exchange sort Algorithmdata structures and algorithms-2018,bs it...
Bubble sort/ Exchange sort Algorithmdata structures and algorithms-2018,bs it...Bubble sort/ Exchange sort Algorithmdata structures and algorithms-2018,bs it...
Bubble sort/ Exchange sort Algorithmdata structures and algorithms-2018,bs it...
Muhammad Abuzar
 
Sorting of arrays, types in c++ .IST .ppt
Sorting of arrays, types in c++ .IST .pptSorting of arrays, types in c++ .IST .ppt
Sorting of arrays, types in c++ .IST .ppt
saadpisjes
 
BUBBLESORT
BUBBLESORT BUBBLESORT
BUBBLESORT
Ashish Sadavarti
 
Bubble Sort presentation.pptx
Bubble Sort presentation.pptxBubble Sort presentation.pptx
Bubble Sort presentation.pptx
TusharTikia
 
Splay trees balance trees in a different way from AVL trees. A.docx
Splay trees balance trees in a different way from AVL trees. A.docxSplay trees balance trees in a different way from AVL trees. A.docx
Splay trees balance trees in a different way from AVL trees. A.docx
mckellarhastings
 
Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]
Muhammad Hammad Waseem
 
Sorting
SortingSorting
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
Zaid Hameed
 
How bubble sort works
How bubble sort worksHow bubble sort works
How bubble sort works
Gaurav Kumar
 

Similar to 8 elementary sorts-bubble (16)

MYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptx
MYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptxMYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptx
MYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptx
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.
 
cs1311lecture16wdl.ppt
cs1311lecture16wdl.pptcs1311lecture16wdl.ppt
cs1311lecture16wdl.ppt
 
Bubble Sort Python
Bubble Sort PythonBubble Sort Python
Bubble Sort Python
 
Bubble Sort.ppt
Bubble Sort.pptBubble Sort.ppt
Bubble Sort.ppt
 
Bubble sort/ Exchange sort Algorithmdata structures and algorithms-2018,bs it...
Bubble sort/ Exchange sort Algorithmdata structures and algorithms-2018,bs it...Bubble sort/ Exchange sort Algorithmdata structures and algorithms-2018,bs it...
Bubble sort/ Exchange sort Algorithmdata structures and algorithms-2018,bs it...
 
Sorting of arrays, types in c++ .IST .ppt
Sorting of arrays, types in c++ .IST .pptSorting of arrays, types in c++ .IST .ppt
Sorting of arrays, types in c++ .IST .ppt
 
BUBBLESORT
BUBBLESORT BUBBLESORT
BUBBLESORT
 
Bubble Sort presentation.pptx
Bubble Sort presentation.pptxBubble Sort presentation.pptx
Bubble Sort presentation.pptx
 
Splay trees balance trees in a different way from AVL trees. A.docx
Splay trees balance trees in a different way from AVL trees. A.docxSplay trees balance trees in a different way from AVL trees. A.docx
Splay trees balance trees in a different way from AVL trees. A.docx
 
Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]
 
Sorting
SortingSorting
Sorting
 
Sorting
SortingSorting
Sorting
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
How bubble sort works
How bubble sort worksHow bubble sort works
How bubble sort works
 

More from irdginfo

Quicksort Presentation
Quicksort PresentationQuicksort Presentation
Quicksort Presentation
irdginfo
 
10 merge sort
10 merge sort10 merge sort
10 merge sortirdginfo
 
9 big o-notation
9 big o-notation9 big o-notation
9 big o-notationirdginfo
 
8 elementary sorts-shell
8 elementary sorts-shell8 elementary sorts-shell
8 elementary sorts-shellirdginfo
 
8 elementary sorts-insertion
8 elementary sorts-insertion8 elementary sorts-insertion
8 elementary sorts-insertionirdginfo
 
8 elementary sorts-selection
8 elementary sorts-selection8 elementary sorts-selection
8 elementary sorts-selectionirdginfo
 
7 searching injava-binary
7 searching injava-binary7 searching injava-binary
7 searching injava-binaryirdginfo
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injavairdginfo
 
5 data structures-hashtable
5 data structures-hashtable5 data structures-hashtable
5 data structures-hashtableirdginfo
 
5 data structures-tree
5 data structures-tree5 data structures-tree
5 data structures-treeirdginfo
 
5 data structures-stack
5 data structures-stack5 data structures-stack
5 data structures-stackirdginfo
 
5 data structures-arraysandlinkedlist
5 data structures-arraysandlinkedlist5 data structures-arraysandlinkedlist
5 data structures-arraysandlinkedlistirdginfo
 
4 character encoding-unicode
4 character encoding-unicode4 character encoding-unicode
4 character encoding-unicodeirdginfo
 
4 character encoding-ascii
4 character encoding-ascii4 character encoding-ascii
4 character encoding-asciiirdginfo
 
4 character encoding
4 character encoding4 character encoding
4 character encodingirdginfo
 
3 number systems-floatingpoint
3 number systems-floatingpoint3 number systems-floatingpoint
3 number systems-floatingpointirdginfo
 
2 number systems-scientificnotation
2 number systems-scientificnotation2 number systems-scientificnotation
2 number systems-scientificnotationirdginfo
 
1 number systems-hex
1 number systems-hex1 number systems-hex
1 number systems-hexirdginfo
 
1 number systems-unsignedsignedintegers
1 number systems-unsignedsignedintegers1 number systems-unsignedsignedintegers
1 number systems-unsignedsignedintegersirdginfo
 
1 number systems-octal
1 number systems-octal1 number systems-octal
1 number systems-octalirdginfo
 

More from irdginfo (20)

Quicksort Presentation
Quicksort PresentationQuicksort Presentation
Quicksort Presentation
 
10 merge sort
10 merge sort10 merge sort
10 merge sort
 
9 big o-notation
9 big o-notation9 big o-notation
9 big o-notation
 
8 elementary sorts-shell
8 elementary sorts-shell8 elementary sorts-shell
8 elementary sorts-shell
 
8 elementary sorts-insertion
8 elementary sorts-insertion8 elementary sorts-insertion
8 elementary sorts-insertion
 
8 elementary sorts-selection
8 elementary sorts-selection8 elementary sorts-selection
8 elementary sorts-selection
 
7 searching injava-binary
7 searching injava-binary7 searching injava-binary
7 searching injava-binary
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
 
5 data structures-hashtable
5 data structures-hashtable5 data structures-hashtable
5 data structures-hashtable
 
5 data structures-tree
5 data structures-tree5 data structures-tree
5 data structures-tree
 
5 data structures-stack
5 data structures-stack5 data structures-stack
5 data structures-stack
 
5 data structures-arraysandlinkedlist
5 data structures-arraysandlinkedlist5 data structures-arraysandlinkedlist
5 data structures-arraysandlinkedlist
 
4 character encoding-unicode
4 character encoding-unicode4 character encoding-unicode
4 character encoding-unicode
 
4 character encoding-ascii
4 character encoding-ascii4 character encoding-ascii
4 character encoding-ascii
 
4 character encoding
4 character encoding4 character encoding
4 character encoding
 
3 number systems-floatingpoint
3 number systems-floatingpoint3 number systems-floatingpoint
3 number systems-floatingpoint
 
2 number systems-scientificnotation
2 number systems-scientificnotation2 number systems-scientificnotation
2 number systems-scientificnotation
 
1 number systems-hex
1 number systems-hex1 number systems-hex
1 number systems-hex
 
1 number systems-unsignedsignedintegers
1 number systems-unsignedsignedintegers1 number systems-unsignedsignedintegers
1 number systems-unsignedsignedintegers
 
1 number systems-octal
1 number systems-octal1 number systems-octal
1 number systems-octal
 

Recently uploaded

Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 

Recently uploaded (20)

Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 

8 elementary sorts-bubble

  • 1. Bubble Sort  Compares adjacent array elements – Exchanges their values if they are out of order  Smaller values bubble up to the top of the array – Larger values sink to the bottom
  • 2. Bubble Sort (cont.)  Example: 512354277 101 0 1 2 3 4 5 Swap42 77
  • 3. Bubble Sort (cont.)  Example: 512357742 101Swap35 77 0 1 2 3 4 5
  • 4. Bubble Sort (cont.)  Example: 512773542 101Swap12 77 0 1 2 3 4 5
  • 5. Bubble Sort (cont.)  Example: 577123542 101 No need to swap 0 1 2 3 4 5
  • 6. Bubble Sort (cont.)  Example: 577123542 101 Swap5 101 0 1 2 3 4 5
  • 7. Bubble Sort (cont.)  Example: 77123542 5 101 Largest value correctly placed 0 1 2 3 4 5
  • 8. Bubble Sort (cont.) • Notice that only the largest value is correctly placed • All other values are still out of order • So we need to repeat this process 77123542 5 101 Largest value correctly placed 0 1 2 3 4 5
  • 9. Bubble Sort (cont.) Repeat “Bubble Up” How Many Times?  If we have N elements…  And if each time we bubble an element, we place it in its correct location…  Then we repeat the “bubble up” process N – 1 times.  This guarantees we’ll correctly place all N elements.
  • 10. Bubble Sort (cont.) 77123542 5 0 1 2 3 4 5 101 5421235 77 0 1 2 3 4 5 101 4253512 77 0 1 2 3 4 5 101 4235512 77 0 1 2 3 4 5 101 4235125 77 0 1 2 3 4 5 101 N-1
  • 11. Bubble Sort (cont.)  What if the array was already sorted?  What if only a few elements were out of place and after a couple of “bubble ups,” the array was sorted?  We want to be able to detect this and “stop early”!
  • 12. Bubble Sort (cont.) Using a Boolean “Flag”  We can use a boolean variable to determine if any swapping occurred during the “bubble up.”  If no swapping occurred, then we know that the collection is already sorted!  This boolean “flag” needs to be reset after each “bubble up.”
  • 13. public static void BubbleSort( int [ ] num ) { int j; boolean flag = true; // set flag to true to begin first pass int temp; //holding variable while ( flag ) { flag= false; //set flag to false awaiting a possible swap for( j=0; j > num.length -1; j++ ) if ( num[ j ] > num[j+1] ) // change to > for ascending sort { temp = num[ j ]; //swap elements num[ j ] = num[ j+1 ]; num[ j+1 ] = temp; flag = true; //shows a swap occurred } } } }
  • 14. Bubble Sort (cont.)  Excellent performance in some cases – But very poor performance in others!  Works best when array is nearly sorted to begin with  Worst case number of comparisons: n2  Worst case number of exchanges: n2  Best case occurs when the array is already sorted: – n comparisons – 0 exchanges