C 语言中的排序算法16
在计算机科学中,排序是将一组数据按照特定顺序(例如升序、降序)排列的过程。C 语言提供了多种排序算法,每种算法都有其独特的优点和缺点。本文将介绍 C 语言中常用的排序算法,并演示如何实现和使用它们。
冒泡排序
冒泡排序是一种简单的排序算法,它通过反复比较相邻元素并交换位置来对数组进行排序。每次迭代,最大的元素都会“冒泡”到数组的末尾。以下是如何在 C 语言中实现冒泡排序:
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]) {
// 交换 arr[j] 和 arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
选择排序
选择排序是一种算法,它通过在剩余未排序元素中找到最小(或最大)元素并将其与当前未排序元素交换来对数组进行排序。以下是如何在 C 语言中实现选择排序:
void selectionSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// 交换 arr[i] 和 arr[minIndex]
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
插入排序
插入排序是一种算法,它通过将每个元素插入到前面已排序的子数组中来对数组进行排序。以下是如何在 C 语言中实现插入排序:
void insertionSort(int arr[], int size) {
for (int i = 1; i < size; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
快速排序
快速排序是一种分治算法,它通过选择一个基准元素,将数组分成两个子数组,然后递归地对这两个子数组进行排序,最后合并结果。以下是如何在 C 语言中实现快速排序:
void quickSort(int arr[], int low, int high) {
if (low < high) {
int partitionIndex = partition(arr, low, high);
quickSort(arr, low, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, high);
}
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j]
2025-02-04
上一篇:C 语言中负数的输出
下一篇:C 语言求余数函数库揭秘
Java数组元素:从基础到高级操作的深度解析
https://www.shuihudhg.cn/134539.html
PHP Web应用的安全基石:全面解析数据库SQL注入防御
https://www.shuihudhg.cn/134538.html
Python函数入门到进阶:用简洁代码构建高效程序
https://www.shuihudhg.cn/134537.html
PHP中解析与提取代码注释:DocBlock、反射与AST深度探索
https://www.shuihudhg.cn/134536.html
Python深度解析与高效处理.dat文件:从文本到二进制的实战指南
https://www.shuihudhg.cn/134535.html
热门文章
C 语言中实现正序输出
https://www.shuihudhg.cn/2788.html
c语言选择排序算法详解
https://www.shuihudhg.cn/45804.html
C 语言函数:定义与声明
https://www.shuihudhg.cn/5703.html
C语言中的开方函数:sqrt()
https://www.shuihudhg.cn/347.html
C 语言中字符串输出的全面指南
https://www.shuihudhg.cn/4366.html