比较排序是一种通过比较元素的大小来确定它们在序列中位置的算法。以下是几种常见比较排序算法的伪代码和C代码实现:
冒泡排序 伪代码
```
for i = 1 to n-1
for j = 1 to n-i
if A[j] > A[j+1]
exchange A[j] with A[j+1]
```
C代码:
```c
include 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]) { 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); bubbleSort(arr, n); printf("Sorted array: \n"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; } ```选择排序
伪代码
```
for i = 1 to n-1
min = i
for j = i+1 to n
if A[j] < A[min]
min = j
if min != i
exchange A[i] with A[min]
```
C代码:
```c
include void selectionSort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { int min_idx = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[min_idx]) { min_idx = j; } } if (min_idx != i) { int temp = arr[i]; arr[i] = arr[min_idx]; arr[min_idx] = temp; } } } int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr) / sizeof(arr); selectionSort(arr, n); printf("Sorted array: \n"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; } ```插入排序
伪代码
```
for i = 1 to n-1
key = A[i]
j = i - 1
while j >= 0 and A[j] > key
A[j + 1] = A[j]
j = j - 1
A[j + 1] = key
```
C代码: