C Programming Language Tutorial
Variables and Data Types
Input/Output
Looping and Selection Structures
Array
Functions
Preprocessing Command
Pointer
Structure
File Operations
Important Knowledge
In this tutorial, we will learn how to sort array elements using the bubble sort method in the C programming language. Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The process continues until the list is sorted.
Here's an example of implementing bubble sort to sort an integer array in ascending order:
#include <stdio.h> void bubbleSort(int arr[], int size) { for (int i = 0; i < size - 1; i++) { for (int j = 0; j < size - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap elements int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { int myArray[] = {64, 34, 25, 12, 22, 11, 90}; int size = sizeof(myArray) / sizeof(myArray[0]); printf("Original array:\n"); printArray(myArray, size); bubbleSort(myArray, size); printf("Sorted array (using bubble sort):\n"); printArray(myArray, size); return 0; }
The output will be:
Original array: 64 34 25 12 22 11 90 Sorted array (using bubble sort): 11 12 22 25 34 64 90
Note that bubble sort has a time complexity of O(n^2), where n is the number of elements in the array. In the worst case, bubble sort makes n*(n-1)/2 comparisons and n*(n-1)/2 swaps, which makes it inefficient for large data sets. However, it is easy to implement and works well for small arrays or arrays that are partially sorted.
That's it for our tutorial on sorting array elements using the bubble sort method in the C programming language. Implementing the bubble sort algorithm is a great way to learn basic sorting techniques and to practice working with arrays and loops in C.
C program for sorting array using bubble sort:
#include <stdio.h> void bubbleSort(int arr[], int n) { for (int i = 0; i < n - 1; ++i) { for (int j = 0; j < n - i - 1; ++j) { if (arr[j] > arr[j + 1]) { // Swap if out of order int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr) / sizeof(arr[0]); // Applying bubble sort bubbleSort(arr, n); // Printing sorted array printf("Sorted array: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }