–
{3,10,9,2,5}
–
After the first pass:{3,9,2,5,10}
–
After the 2
nd
pass:{3,2,5,9,10}
–
After the 3
rd
pass:{2,3,5,9,10}
–
After the 4
th
pass:{2,3,5,9,10}
–
The algorithm now is done, the remaining number at the
beginning doesn’t need to be examined as it is the only number
left and must be the smallest.
–
Its worst and average complexity is O(N
2
)
–
Its best complexity is O(N).

BUBBLE SORT
// sorts array of integers using bubble sort
int main()
{
int a[]={3,10,9,2,5,20,15,0};
bubble(a,8);
cout<<"The array sorted is : \n";
for(int i=0;i<8;i++)
{
cout<<a[i]<<" ";
}
return 0;
}
void bubble(int a[],int size)
{
//move largest number toward the right
for(int i=size-1;i>0;i--)
{
for(int j=0;j<i;j++)
{
if(a[j]>a[j+1])
{
swap(a[j],a[j+1]);
}
}
}
OUTPUT
The array sorted is :
0 2 3 5 9 10 15 20

INSERTION SORT
•
It
is similar to selection sort.
•
The array is divided into two parts at the beginning:
–
sorted part which contains the first element of the array
–
Unsorted part which contains the rest of the elements of the
array
–
At every step, it takes first element in the unsorted part and
inserts
it to the right place in the sorted part.
–
When unsorted part becomes empty, algorithm
stops
•
Insertion sort's overall worst and average case complexity
is O(n
2
) as shifting or swapping methods are used
•
The best case complexity is O(n) where insertion sort is
applied to a sorted array.

INSERTION SORT
void swap(int& a,int& b);
void main()
{
int a[]={20,3,5,1,6,15,10};
int start, current;
//start from a[1] and compare
for (start = 1; start < 7; start++)
{
current = start;
while (current > 0 && a[current] < a[current-1])
{
swap(a[current], a[current-1]);
current--;
}
}
//output the sorted array
for(int i=0;i<7;i++)
{
cout<<a[i]<<" ";
}
}
void swap(int& a,int& b)
{
int t=a;
a=b;
b=t;
}
OUTPUT
The sorted array :
1 3 5 6 10 15 20

#### You've reached the end of your free preview.

Want to read all 16 pages?

- Fall '18
- Eric Swartz