BUBBLE
SORT
BUBBLE
SORT Student’s name:
Bùi Đức Minh 1751057
Phạm Đăng Khôi 1651125
Nguyễn Trần Nguyên Khang 1651046
Võ Ngọc Đại Hải 1651030
Nguyễn Phúc Thiên Ân 1652039
INTRODUCTION
PROBLEM
• Sorting algorithm
• Types of sorting algorithm
BUBBLE
SORT
SORTING
ALGORITHM
Type of sorting algorithm
• Selection sort
• Quick sort
• Merge sort
• Bubble sort
• etc
BUBBLE
SORT
BUBBLE
BUBBLE
BUBBLE
BUBBLE
SORT
SORT
Describe object
• The elements will be arranged in
the order from the biggest to the
smallest
• Comparing each pair of items
• Swapping them
• Repeatedly stepping through lists
that need to be sorted
BUBBLE
SORT
THE ALGORITHM
THE ALGORITHM
“ Bubble” part of Bubble Sort
5
BUBBLE
SORT
THE ALGORITHM
“ Bubble” part of Bubble Sort
1
35
BUBBLE
SORT
COMPLEXITY
BUBBLE
SORT
THE PROCEDURE
• Comparing the value
• Swapping
BUBBLE
SORT
COMPARING THE VALUE
• Assume that we have an array:
A= { 1,3,5,2 }
Compare with A[1]
1 3 5 2 1 3 5 2
1 3 5 2
BUBBLE
SORT
COMPARING THE VALUE
Compare with A[2]
1 3 5 2 1 3 5 2
1 2 5 3
BUBBLE
SORT
COMPARING THE VALUE
Compare with A[3]
1 2 5 3 1 2 3 5
BUBBLE
SORT
THE SWAPPING
We have 2 cups of water
X Y
BUBBLE
SORT
THE SWAPPING
If we just pour the water from Y to X
WTF man?
Idiots!
Gà!
Ngu!
X
Óc cko!
BUBBLE
SORT
THE SWAPPING
We need a third empty cup
Temp
or Z
X Y
or whatever
you want
BUBBLE
SORT
THE SWAPPING
Pour water from X to Temp and X is an empty cup then
X Y Temp = X
BUBBLE
SORT
THE SWAPPING
• Pour water from Y to X and Y is an empty cup then
X=Y Y Temp = X
BUBBLE
SORT
THE SWAPPING
Pour water from Temp to Y and Temp is an empty cup then
X=Y Y=Temp=X Temp
BUBBLE
SORT
FLOW CHART
FLOWCHART
• First read the array from the user.
• Start by comparing the first element of
the array with the second element.
• In case if the first element is greater
than the second element, we will swap
both the elements, and then move on to
compare the second and the third
element, and continue till the end so
on.
FLOWCHART
• If the first element is lesser than the
second element then we move to the
second and compare it with the third
element and move so on.
• In case the is greater we follow the step
4 and if it'sless we follow step 5. Both
of the are discussed above.
• We follow the same process until the
given array is sorted.
THE CODE
#include <iostream>
using namespace std;
main()
{
int a[6];
int i,j,n,temp;
for(i=1;i<=5;i++) //assume there are 5 values in
the array
{
cout<<"Nhap a "<<i<<": ";
cin>>a[i];
}
BUBBLE
SORT
THE CODE
for(i=1;i<=4;i++)
{
for(j=i;j<=5;j++)
if (a[i]>a[j]) //If the value at i is greater than
the value at j
{
temp=a[j]; //swaping
a[j]=a[i];
a[i]=temp;
}
}
for(i=1;i<=5;i++) //print the array on the screen
{
cout<<a[i]<<" ";
}
}
PROGRAM
PROGRAM
• Needed Functions: Swap & 2 For loops
BUBBLE
SORT
PROGRAM
User interface
BUBBLE
SORT