**Write a C program to sort the elements of an array using bubble sort.**

WAP to sort elements of an array in increasing order.

How to sort elements of an integer array.

WAP to sort elements of an array in increasing order.

How to sort elements of an integer array.

#### Required Knowledge

Given an unsorted integer array, we have to sort the elements of the array in increasing order.As the index of the array increases values of the elements should also increase.

For Example:

Input Array : 2 8 4 9 1 0

Output Array : 0 1 2 4 8 9

**Algorithm to sort an array using bubble sort**

*Let inputArray is an integer array having N elements.*

- Bubble sort compares two adjacent element of an array and will swap them if they are out of order. If inputArray [i] > inputArray[i+1] then we will swap elements at position i and i+1 as they are not in increasing order. As we are sorting in increasing order, element at index i must be smaller than element in i+1 in sorted array.
- If inputArray [i] <= inputArray[i+1] then we should not swap elements at position i and i+1 as they are already in increasing order.
- Next, we will compare i+1 and i+2, then i+2 amd i+3 and so on... till end of the array.
- If there are N element then we have to repeat above process N-1 times because in every traversal we will put largest element of unsorted sub-array in its sorted position.

## C program to sort an array in increasing order using bubble sort

#include <stdio.h> #include <conio.h> int main() { int inputArray[100], elementCount, index, i, j, temp; printf("Enter Number of Elements in Array\n"); scanf("%d", &elementCount); printf("Enter %d numbers \n", elementCount); /* Read array elements */ for(index = 0; index < elementCount; index++){ scanf("%d", &inputArray[index]); } /* Sort Array using Bubble Sort */ for(i = 0; i < elementCount; i++) { for(j = 0; j < elementCount-i-1; j++) { if(inputArray[j] > inputArray[j+1]) { /* Swap inputArray[j] and inputArray[j+1] */ temp = inputArray[j]; inputArray[j] = inputArray[j+1]; inputArray[j+1] = temp; } } } printf ("Sorted Array in Increasing Order\n") ; /* Print Sorted Array */ for(index = 0; index < elementCount; index++){ printf("%d ", inputArray[index]); } getch(); }Output

Enter Number of Elements in Array 7 Enter 7 numbers 9 1 0 3 5 2 6 Sorted Array in Increasing Order 0 1 2 3 5 6 9

Enter Number of Elements in Array 8 Enter 8 numbers 1 2 1 2 1 2 1 2 Sorted Array in Increasing Order 1 1 1 1 2 2 2 2

**Related Topics**