By: Sanjeev Sultania Assistant Professor BKBIET, Pilani

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

By: Sanjeev Sultania

Assistant Professor
BKBIET, Pilani
 Sorting means arranging a set of data in
some order.
 There are different methods that are used
to sort the data in ascending or
descending order.

By: Sanjeev Sultania


2
 Bubble sorting is a simple sorting technique in
sorting algorithm.
 In bubble sorting algorithm, we arrange the
elements of the list by forming pairs of
adjacent elements.
 It means we repeatedly step through the list
which we want to sort, compare two items at a
time and swap them if they are not in the right
order.
 Another way to visualize the bubble sort
algorithm is as its name, the smaller element
bubble to the top.

By: Sanjeev Sultania


3
 Bubble Sort is an algorithm which is used to sort
N elements that are given in a memory for eg: an
Array with N number of elements. Bubble Sort
compares all the element one by one and sort
them based on their values.
 It is called Bubble sort, because with each
iteration the smaller element in the list bubbles
up towards the first place, just like a water
bubble rises up to the water surface
 Sorting takes place by stepping through all the
data items one-by-one in pairs and comparing
adjacent data items and swapping each pair that
is out of order.

By: Sanjeev Sultania


4
7 2 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8

2 7 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8

2 7 8 5 4 2 5 7 4 8 2 4 5 7 8 (done)

2 7 5 8 4 2 5 4 7 8

2 7 5 4 8

By: Sanjeev Sultania


5
Let A[5] is an array of 5 elements
TEMP is the variable used for swapping of array elements.
Step 1. Begin
Step 2. Read 5 elements of array A.
Step 3. Write Original Array A.
Step 4. Repeat Steps 4 to 5 for I = 0 to 3.
Step 5. Repeat Step 5for J = 0 to 4 – I.
IF A[J] > A[J+1] : then [Interchange A[J] & A[J+1]
Set TEMP = A[J+1].
Set A[J+1] = A[J]
Set A[J] = TEMP
[End of IF structure].
[End of Step 5 loop].
[End of Step 4 loop].
Step 6. Write Sorted array A.
Step 7. Exit
By: Sanjeev Sultania
6
#include <stdio.h>
void main(){
int a[6] = {5, 1, 6, 2, 4, 3};int i, j, temp; int flag=0;
for(i=0; i<6; i++){
for(j=0; j<6-i-1; j++){
flag = 0; //taking a flag variable
if( a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
flag = 1; //setting flag as 1, if swapping occurs
} }
if(!flag) { //breaking out of for loop if no swapping takes place
break;
} }
for(i=0;i<6;i++)
printf("%d\t",a[i]);
}
By: Sanjeev Sultania
7
 It's
the slowest type of sort... Imagine
comparing and swapping a list of 300
elements, analyzing pair by pair. The
process gets long!
 Experts advise against the use of the
bubble sort for repetitive sorts or sorts
that contain more than a few hundred
objects.

By: Sanjeev Sultania


8

You might also like