You are on page 1of 11

BUBBLE

SORTING
Oliveros, John Erickson D.
IT-13
TOPIC TO BE DISCUSSED

HEADER & DECLARATIONS


ARRAY INPUT
SORTING PROCESS
HEADER & DECLARATIONS
#include <iostream>
using namespace std;
int main()
{
int i,j,k,n,a[50];

VARIABLES
n - size of elements
a[50] - array name
I,j - for loop variables
k - temporary holding for swapping
ARRAY INPUT
OUTPUT:
cout<<"How many number you want to Enter the size of an element:
display?"<<endl; cin>>n; 5
cout<<"Enter the elements: "<<endl; Enter the 5 elements:
for(i = 0; i < n; i++) 21345
cin>>a[i];

LOOP SIMULATION:
n=5; i=0 ; i<5 0 1 2 3 5

2 1 4 5
3
cin>>a[i];

i++
SORTING PROCESS
for(j = 0; j < n; j++)
for(i = 0; i < n-1; i++)
if(a[i] > a[i + 1])
{ k = a[i + 1];
a[i + 1] = a[i];
a[i] = k;
}

LOOP SIMULATION: 0 1 2 3 4
n=5 i=0 → i<n → i<5 → 0<5
j=0 ; j< 5-0 → 0<5 2 1 4 3 5

(a[i]>a[i+1])
a[0]>a[1]
2>1 -> true
SORTING PROCESS 0 1 2 3 4

2 1 3 4 5

LOOP SIMULATION: k = a[i+1]; -> k = a[1] -> k=1


for(j = 0; j < n; j++)
for(i = 0; i < n-1; i++) 0 1 2 3 4

k = a[i+1]; -> k = a[1] -> k=1 2 2 3 4 5


a[i+1]= a[i]; -> a[1] = a[i] -> a[1] = 2
a[i]=k -> a[1]=k -> a[0]=1
a[i+1]= a[i]; -> a[1] = a[i] -> a[1] = 2
0 1 2 3 4

1 2 3 4 5

a[i]=k -> a[1]=k -> a[0]=1


SORTING PROCESS

LOOP SIMULATION:
for(j = 0; j < n; j++)
for(i = 0; i < n-1; i++) 0 1 2 3 4
(a[i]>a[i+j])
a[1]>a[1+1] 1 2 4 3 5
2>3
false
SORTING PROCESS
for(j = 0; j < n; j++)
for(i = 0; i < n-1; i++)
if(a[i] > a[i + 1])
{ k = a[i + 1];
a[i + 1] = a[i];
a[i] = k;
}

LOOP SIMULATION: 0 1 2 3 4
n=5 i=0 → i<n → i<5 → 0<5
j=0 ; j< 5-0 → 0<5 1 2 4 3 5

(a[i]>a[i+1])
a[2]>a[2+1]
4>3 -> true
SORTING PROCESS 0 1 2 3 4

1 2 3 4 5

LOOP SIMULATION: k = a[i+1]; -> k = a[3] -> k=3


for(j = 0; j < n; j++)
for(i = 0; i < n-1; i++) 0 1 2 3 4

k = a[i+1]; -> k = a[3] -> k=3 1 2 3 3 5


a[i+1]= a[i]; -> a[2+1] = 4 -> a[2+1] = 4
a[i]=k -> a[2]=k -> a[2]=3
a[i+1]= a[i]; -> a[2+1] = 4 -> a[2+1] = 4
0 1 2 3 4

1 2 3 4 5

a[i]=k -> a[2]=k -> a[2]=3


SORTING PROCESS

LOOP SIMULATION:
for(j = 0; j < n; j++)
for(i = 0; i < n-1; i++) 0 1 2 3 4
(a[i]>a[i+j])
a[3]>a[3+1] 1 2 3 4 5
4>5
false
SORTING PROCESS

OUTPUT:

LOOP SIMULATION: Step 5 : 3 4 5 6 8


num=5 x=4 → x<num → x<5 → 4<5
y=1; y < 5-4→ 1<1 → false 0 1 2 3 4

cout<<"Result:"<<endl; 3 4 5 6 8
for(i = 0; i < n; i++)
cout<<a[i]<<endl;
return 0;
}

x++

You might also like