定义一个包含10个数字元素的顺序表,并分别用直接插入排序,选择排序,冒泡排序,希尔排序,快速排序,堆排序进行大到小排序 ,要求使用C语言,并定义子函数
时间: 2024-01-07 22:03:40 浏览: 69
好的,以下是一个示例程序,包含了10个数字元素的顺序表,并使用了直接插入排序、选择排序、冒泡排序、希尔排序、快速排序和堆排序进行从大到小排序的过程。请注意,程序中定义了多个子函数来实现各种排序算法。
```c
#include <stdio.h>
#define MAX_SIZE 10
// 直接插入排序
void insertion_sort(int arr[], int n) {
int i, j, temp;
for (i = 1; i < n; i++) {
temp = arr[i];
j = i - 1;
while (j >= 0 && arr[j] < temp) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
// 选择排序
void selection_sort(int arr[], int n) {
int i, j, max_idx, temp;
for (i = 0; i < n - 1; i++) {
max_idx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] > arr[max_idx]) {
max_idx = j;
}
}
temp = arr[i];
arr[i] = arr[max_idx];
arr[max_idx] = temp;
}
}
// 冒泡排序
void bubble_sort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// 希尔排序
void shell_sort(int arr[], int n) {
int i, j, gap, 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;
}
}
}
// 快速排序
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
int temp, j;
for (j = low; j <= high - 1; j++) {
if (arr[j] >= pivot) {
i++;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
void quick_sort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quick_sort(arr, low, pi - 1);
quick_sort(arr, pi + 1, high);
}
}
// 堆排序
void max_heapify(int arr[], int n, int i) {
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
int temp;
if (l < n && arr[l] > arr[largest]) {
largest = l;
}
if (r < n && arr[r] > arr[largest]) {
largest = r;
}
if (largest != i) {
temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
max_heapify(arr, n, largest);
}
}
void heap_sort(int arr[], int n) {
int i, temp;
for (i = n / 2 - 1; i >= 0; i--) {
max_heapify(arr, n, i);
}
for (i = n - 1; i >= 0; i--) {
temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
max_heapify(arr, i, 0);
}
}
// 打印数组元素
void print_array(int arr[], int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[MAX_SIZE] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int n = MAX_SIZE;
printf("Original array:\n");
print_array(arr, n);
insertion_sort(arr, n);
printf("After insertion sort:\n");
print_array(arr, n);
selection_sort(arr, n);
printf("After selection sort:\n");
print_array(arr, n);
bubble_sort(arr, n);
printf("After bubble sort:\n");
print_array(arr, n);
shell_sort(arr, n);
printf("After shell sort:\n");
print_array(arr, n);
quick_sort(arr, 0, n - 1);
printf("After quick sort:\n");
print_array(arr, n);
heap_sort(arr, n);
printf("After heap sort:\n");
print_array(arr, n);
return 0;
}
```
阅读全文