Professional Documents
Culture Documents
Cost
Time
For i <--- to length[Array] -1
C1
n
do For j<--- to length[Array] - i
C2
(n-1)
(n-i+1)
do if (Array[j]>Array[j+1])
C3
(n-1)(n-i)
then exchange Array[j] Array[j+1]
C4
(n-1)(n-i)
Now we will see how it works by taking the example of any array as follows:
n-1
______________________________________________________
| [5]<---j
[4]
[4]
[4]
[4] |
[4]<---j+1
[5]<---j
[3]
[3]
[3]
[3]
[3]<---j+1
[5]<---j
[2]
[2]
[2]
[2]
[2]<---j+1 [5]<---j
[1]
[1]
[1]
[1]
[1]<---j+1 [5]
1st iteration :
* j and j+1 are two pointer set at initial position i.e element [5] and element [4].
* i will iterate till n-1 at first time ,this is the array of length 5 thats why 5-1=4
times it will be iterared.
* At line 3 if (Array[j]>Array[j+1])
At line 4 then exchange
Array[j]Array[j+1]
[5] > [4] true
exchange [5] [4]
[5] > [3] true
exchange [5] [3]
[5] > [2] true
exchange [5] [2]
[5] > [1] true
exchange [5] [1]
* Here you will notice element [5] is set to its proper position.
n-2
_________________________________________________
[4]<---j
[3]<---j+1
[2]
[1]
[5]
[3]
[4]<---j
[2]<---j+1
[1]
[5]
[3]
[2]
[4]<---j
[1]<---j+1
[5]
[3]
[2]
[1]
[4]
[5]
2nd iteration:
* Again j and j+1 are two pointer set at initial position i.e at element [4] and
element [3].
* In above figure i will iterate n-2 times i.e array length is 5 which means 5-2=3
times it will iterate.
* At line 3 if (Array[j]> Array[j+1])
At line 4 then exchange Array[j]
Array[j+1]
[4] > [3] true
exchange [4] [3]
[4] > [2] true
exchange [4] [2]
[4] > [1] true
exchange [4] [1]
[4] > [5] false
no exchange
* Here in this 2nd iteration element [4] is set in its proper position.
n-3
______________________________
| [3]<---j
[2]
[2]
|
[2]<---j+1
[1]
[4]
[5]
[3]<---j
[1]<---j+1
[4]
[5]
[1]
[3]
[4]
[5]
3rd iteration:
* j and j+1 pointers are set to its position according to algorithm.
* In above figure i will iterate n-3 times i.e array length is 5 which means 53=2 times it will iterate.
*At line 3 if (Array[j]>Array[j+1])
At line 4 then exchange
Array[j] Array[j+1]
[3] > [2] true
exchange [3] [2]
[3] > [1] true
exchange [3] [1]
[3] > [4] false
no exchange
* Here in this 3rd iteration element [3] is set in its proper position.
n-4
________________________
| [2]<---j
[1]
|
[1]<---j+1
[3]
[4]
[5]
[2]
[3]
[4]
[5]
4th iteration:
* j and j+1 pointer are set to its position according to algorithm.
* In above figure i iterator will iterate n-4 times i.e array length is 5 which
means 5-4=1 times it will iterate.
* At line 3 if(Array[j]>Array[j+1])
At line 4 then exchange
Array[j] Array[j+1]
[2] > [1] true
exchange [2] [1]
[2] > [3] false
no exchange
* Here this is our array's final iteration in which element[1] and element[2] are
set to their proper position
respectively in the array.