以下是不同类型的排序算法的C语言实现示例:
- 冒泡排序
void bubble_sort(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(&arr[j], &arr[j+1]);
}
}
}
}
- 插入排序
void insertion_sort(int arr[], int n) {
int i, j, key;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
}
- 选择排序
void selection_sort(int arr[], int n) {
int i, j, min_index;
for (i = 0; i < n-1; i++) {
min_index = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[min_index]) {
min_index = j;
}
}
swap(&arr[i], &arr[min_index]);
}
}
- 希尔排序
void shell_sort(int arr[], int n) {
int gap, i, j, temp;
for (gap = n/2; gap > 0; gap /= 2) {
for (i = gap; i < n; i++) {
temp = arr[i];
for (j = i; j >= gap && arr[j-gap] > temp; j -= gap) {
arr[j] = arr[j-gap];
}
arr[j] = temp;
}
}
}
- 快速排序
void quick_sort(int arr[], int left, int right) {
if (left >= right) {
return;
}
int pivot = arr[left];
int i = left, j = right;
while (i < j) {
while (i < j && arr[j] >= pivot) {
j--;
}
arr[i] = arr[j];
while (i < j && arr[i] <= pivot) {
i++;
}
arr[j] = arr[i];
}
arr[i] = pivot;
quick_sort(arr, left, i-1);
quick_sort(arr, i+1, right);
}
- 归并排序
void merge_sort(int arr[], int l, int r) {
if (l >= r) {
return;
}
int mid = (l + r) / 2;
merge_sort(arr, l, mid);
merge_sort(arr, mid+1, r);
merge(arr, l, mid, r);
}
void merge(int arr[], int l, int mid, int r) {
int i = l, j = mid + 1, k = 0;
int temp[r-l+1];
while (i <= mid && j <= r) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
}
}
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= r) {
temp[k++] = arr[j++];
}
for (int i = 0; i < k; i++) {
arr[l+i] = temp[i];
}
}
- 堆排序
void heap_sort(int arr[], int n) {
for (int i = n/2-1; i >= 0; i--) {
heapify(arr, i, n);
}
for (int i = n-1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
heapify(arr, 0, i);
}
}
void heapify(int arr[], int i, int n) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
if (largest != i) {
swap(&arr[largest], &arr[i]);
heapify(arr, largest, n);
}
}
以上就是几个常见的排序算法的C语言实现示例,可以通过这些代码加深对它们的理解和掌握。