选择排序法冒泡排序c语言
时间: 2023-12-02 11:43:15 浏览: 110
C语言冒泡排序法的实现(升序排序法)
以下是选择排序和冒泡排序的C语言代码示例:
选择排序:
```c
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, min_idx, tmp;
for (i = 0; i < n-1; i++) {
min_idx = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
tmp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = tmp;
}
}
int main() {
int arr[] = {2, 1, 34, 5};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
冒泡排序:
```c
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, tmp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
}
int main() {
int arr[] = {2, 1, 34, 5};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
阅读全文