以下是几个经典的算法的C语言程序示例:
1. 快速排序(Quick Sort):
- 输入:在程序中,你可以修改`int arr[]`数组的内容和大小,来进行不同的排序。
- 输出:程序将输出原始数组和排序后的数组。
#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int size = sizeof(arr) / sizeof(arr[0]);
printf("原始数组:");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
quickSort(arr, 0, size - 1);
printf("\n排序后的数组:");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
2. 归并排序(Merge Sort):
- 输入:在程序中,你可以修改`int arr[]`数组的内容和大小,来进行不同的排序。
- 输出:程序将输出原始数组和排序后的数组。
#include <stdio.h>
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int size = sizeof(arr) / sizeof(arr[0]);
printf("原始数组:");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
mergeSort(arr, 0, size - 1);
printf("\n排序后的数组:");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
3. 二分查找(Binary Search):
- 输入:在程序中,你可以修改`int arr[]`数组的内容和大小,来进行不同的查找。同时,你可以修改`int target`变量的值,来指定你要查找的目标元素。
- 输出:如果目标元素在数组中,程序将输出目标元素在数组中的索引;如果目标元素不在数组中,程序将输出"目标元素不在数组中"。
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int target) {
if (right >= left) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] > target)
return binarySearch(arr, left, mid - 1, target);
return binarySearch(arr, mid + 1, right, target);
}
return -1;
}
int main() {
int arr[] = {2, 3, 4, 10, 40};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 10;
int result = binarySearch(arr, 0, size - 1, target);
if (result == -1)
printf("目标元素不在数组中\n");
else
printf("目标元素在数组中的索引为 %d\n", result);
return 0;
}
|
|