SlideShare une entreprise Scribd logo
1  sur  14
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

Contenu connexe

Similaire à 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.pptxArjayBalberan1
 
Bubble sort
Bubble sortBubble sort
Bubble sortManek Ar
 
ds 3Sorting.ppt
ds 3Sorting.pptds 3Sorting.ppt
ds 3Sorting.pptAlliVinay1
 
Data Structure and Algorithms Sorting
Data Structure and Algorithms SortingData Structure and Algorithms Sorting
Data Structure and Algorithms SortingManishPrajapati78
 
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
 
Bubble Sort Python
Bubble Sort PythonBubble Sort Python
Bubble Sort PythonValneyFilho1
 
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 .pptsaadpisjes
 
Bubble Sort presentation.pptx
Bubble Sort presentation.pptxBubble Sort presentation.pptx
Bubble Sort presentation.pptxTusharTikia
 
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.docxmckellarhastings
 
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-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdfSorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdfArjunSingh81957
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithmsZaid Hameed
 
How bubble sort works
How bubble sort worksHow bubble sort works
How bubble sort worksGaurav Kumar
 

Similaire à 8 elementary sorts-bubble (19)

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
 
ds 3Sorting.ppt
ds 3Sorting.pptds 3Sorting.ppt
ds 3Sorting.ppt
 
Data Structure and Algorithms Sorting
Data Structure and Algorithms SortingData Structure and Algorithms Sorting
Data Structure and Algorithms Sorting
 
Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.
 
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-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdfSorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
 
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
 

Plus de irdginfo

Quicksort Presentation
Quicksort PresentationQuicksort Presentation
Quicksort Presentationirdginfo
 
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
 

Plus de 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
 

Dernier

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 

Dernier (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 

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