- n元数组归并排序(从小到大)(分治算法)
#include<stdio.h>
void Merge(int a[], int b[], int left, int mid, int right) {
int i = left, j = mid + 1, k = left;
while (i <= mid && j <= right) {
if (a[i] <= a[j]) {
b[k++] = a[i++];
} else {
b[k++] = a[j++];
}
}
while (i <= mid) {
b[k++] = a[i++];
}
while (j <= right) {
b[k++] = a[j++];
}
for (i = left; i <= right; i++) {
a[i] = b[i];
}
}
void MergeSort(int a[], int b[], int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
MergeSort(a, b, left, mid);
MergeSort(a, b, mid + 1, right);
Merge(a, b, left, mid, right);
}
}
int main() {
int n;
printf("输入n元数组n的值:");
scanf("%d", &n);
int a[n], b[n];
printf("输入数组的值:");
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
MergeSort(a, b, 0, n - 1);
for (int j = 0; j < n; j++) {
printf("%d\t", a[j]);
}
return 0;
}
2. n元数组快速排序(从小到大)(分治算法)
#include<stdio.h>
int partition(int A[], int low, int high) {
int pivot = A[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (A[j] < pivot) {
i++;
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
int temp = A[i + 1];
A[i + 1] = A[high];
A[high] = temp;
return (i + 1);
}
void quicksort(int A[], int low, int high) {
if (low < high) {
int k = partition(A, low, high);
quicksort(A, low, k - 1);
quicksort(A, k + 1, high);
}
}
int main() {
int n;
printf("输入n元数组n的值:");
scanf("%d", &n);
int a[n];
printf("输入数组的值:");
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
quicksort(a, 0, n - 1);
for (int j = 0; j < n; j++) {
printf("%d\t", a[j]);
}
return 0;
}