The bubble sort Algorithm simply compares adjacent elements and exchanges them if they are out of order.

To apply the Bubble Sort we follow the following steps.

- Compare 1st two elements and exchange them if they are out of order.
- Move down one element and compare 2nd and 3rd elements. Exchange if necessary. Continue until end of array.
- Pass through array again, repeating process and exchanging as necessary.
- Repeat until a pass is made with no exchanges.

Question : Write a c program for quick sort.

In this lesson we will learn how to write a source code in C programming language for doing simple bubble sort using array in ascending order.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
/** Bubble Sort Algorithm C Example by Codebind.com */ #include <stdio.h> #include <stdlib.h> void PrintArray(int *array, int n) { for (int i = 0; i < n; ++i) printf("%d ", array[i]); printf("\n"); } void BubbleSort(int array[], int n) { bool swapped = true; int j = 0; int temp; while (swapped) { swapped = false; j++; for (int i = 0; i < n - j; ++i) { if (array[i] > array[i + 1]) { temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; swapped = true; } } } } int main() { int array[] = {94, 42, 50, 95, 333, 65, 54, 456, 1, 1234}; int n = sizeof(array)/sizeof(array[0]); printf("Before Bubble Sort :\n"); PrintArray(array, n); BubbleSort(array, n); printf("After Bubble Sort :\n"); PrintArray(array, n); return (0); } /* OUTPUT Before Bubble Sort : 94 42 50 95 333 65 54 456 1 2325 After Bubble Sort : 1 42 50 54 65 94 95 333 456 2325 */ |