# 排序算法：查找最小的k个元素

#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
#include
#define N 6
int partition(int a[], int low, int high)
{
int key = a[low];
a[0] = a[low];
while (low < high)
{
while (low < high&&a[high] >= key)
{
high–;
}
a[low] = a[high];
while (low < high&&a[low] <= key)
{
low++;
}
a[high] = a[low];
}
a[low] = a[0];
return low;
}
void qsort(int a[], int low, int high)
{
int p;
if (low < high)
{
p = partition(a, low, high);
qsort(a, low, p – 1);
qsort(a, p + 1,high);
}
}
void output(int a[], int num)
{
for (int i = 1; i <= num; i++)
{
printf(“%d “, a[i]);
}
}
void main()
{
int a[N];
int num;
printf(“请输入数字个数n”);
scanf(“%d”, &num);
for (int i = 0; i < num; i++)
{
scanf(“%d”, &a[i]);
}
qsort(a, 1, 5);
printf(“n”);
printf(“请输入最小的n个元素n”);
int n;
scanf(“%d”, &n);
output(a, n);
system(“pause”);
}

#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
#include
#define N 6
void heapjust(int a[], int i, int length)
{
int child = 0, tmp;
for (tmp = a[i]; 2 * i + 1
{
child = 2 * i + 1;
if (child < length - 1 && a[child+1] < a[child])
{
child++;
}
if (tmp>a[child])
{
a[i] = a[child];
}
else
{
break;
}
a[child] = tmp;
}
}
int getmin(int a[], int i, int length)
{
int min = a[0];
a[0] = a[length-1];
a[length-1] = min;
int tmp, child = 0;
int k = 0, j = i – 1;
for (tmp = a[0];2 * k + 1 < length-1; k = child)
{
child = 2 * k + 1;
if (child < length - 2 && a[child + 1] < a[child])
{
child++;
}
if (tmp>a[child])
{
a[k] = a[child];
}
else
{
break;
}
a[child] = tmp;
}
return min;
}
void kmin(int a[], int length, int k)
{
for (int i = length – 1; i >= 0; i–)
{
heapjust(a, i, length);
}
int j = length;
for (int i = k; i > 0; i–, j–)
{
int min = getmin(a, i, j);
printf(“%d  n”, min);
}
}
void main()
{
int a[N];
int num;
printf(“请输入数字个数n”);
scanf(“%d”, &num);
for (int i = 0; i < num; i++)
{
scanf(“%d”, &a[i]);
}
kmin(a, num, 3);
system(“pause”);
}

Tags: