In C programming, sorting refers to the process of arranging elements in a specific order. The most common sorting order is ascending or descending numerical order, but elements can also be sorted based on other criteria, such as alphabetical order, frequency, or any custom-defined comparison.
Sorting is a fundamental algorithmic operation and is widely used in various applications, such as searching, data analysis, and optimisation. There are several sorting algorithms available in C programming, each with its own strengths and weaknesses. The choice of sorting algorithm depends on the size of the data, the distribution of the data, and the specific requirements of the application.
Let's discuss the commonly used Bubble Sort algorithm in C programming:
- Bubble Sort:
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 pass through the list is repeated until the list is sorted.
Example implementation of Bubble Sort in C:
c#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
bubbleSort(arr, n);
printf("\nSorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
No comments:
Post a Comment