You are on page 1of 8

(http://www.c4learn.

com/c-
programs/)

Table of Content

C Program to Implement Insertion Sort in C Programming (http://www.c4learn.com/c-

programs/program-to-implement-insertion-sort-in-c-programming.html)

C Program to Sort Structures on the basis of Structure Element (http://www.c4learn.com/c-

programs/sorting-elements-of-structure.html)

C Program to Implement Bubble Sort in C Programming

C Program to Sort the list of Strings (http://www.c4learn.com/c-programs/c-program-for-sorting-

the-list-of-strings.html)

C Program to Sort array of Structure (http://www.c4learn.com/c-programs/c-program-to-sort-

array-of-structure-in-c-programming.html)

C Program to Implement Bubble Sort in C Programming

Bubble Sort in C : All Passes


(http://www.blogger.com/post-edit.g?

blogID=4505317275190539500&postID=5323925993959243257)

Program :

#include<stdio.h>
#include<conio.h>

void bubble_sort(int[], int);

void main() {
int arr[30], num, i;

printf("\nEnter no of elements :");
scanf("%d", &num);

printf("\nEnter array elements :");
for (i = 0; i < num; i++)
scanf("%d", &arr[i]);

bubble_sort(arr, num);
getch();
}

void bubble_sort(int iarr[], int num) {
int i, j, k, temp;

printf("\nUnsorted Data:");
for (k = 0; k < num; k++) {
printf("%5d", iarr[k]);
}

for (i = 1; i < num; i++) {
for (j = 0; j < num - 1; j++) {
if (iarr[j] > iarr[j + 1]) {
temp = iarr[j];
iarr[j] = iarr[j + 1];
iarr[j + 1] = temp;
}
}

printf("\nAfter pass %d : ", i);
for (k = 0; k < num; k++) {
printf("%5d", iarr[k]);
}
}
}

What Happens After Each Iteration ?

1. There are N number of Unsorted Elements


2. Total Number of Iterations = N-1

3. At the End of First Iteration : Largest Element Will get its Exact Final Position

4. At the End of 2nd Iteration : 2nd Largest Element Will get its Exact Final Position

5. .

6. .
7. .

8. .

9. At the End of (N-1)th Iteration : (N-1)th Largest Element Will get its Exact Final Position

Output :

Enter no of elements :5
Enter array elements :10 4 55 21 6

Unsorted Data: 10 4 55 21 6
After pass 1 : 4 10 21 6 55
After pass 2 : 4 10 6 21 55
After pass 3 : 4 6 10 21 55
After pass 4 : 4 6 10 21 55

Visual Explanation :
(http://c4learn.com/wp-content/uploads/2010/11/Bubble_sort_Visual_animation.jpg)
Copyright 2015. All Rights Reserved.

You might also like