Professional Documents
Culture Documents
SORTING
Oliveros, John Erickson D.
IT-13
TOPIC TO BE DISCUSSED
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
1 2 3 4 5
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
1 2 3 4 5
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:
cout<<"Result:"<<endl; 3 4 5 6 8
for(i = 0; i < n; i++)
cout<<a[i]<<endl;
return 0;
}
x++