查找最小的 k 個元素
題目:輸入 n 個整數,輸出其中最小的 k 個。
例如輸入 1,2,3,4,5,6,7 和 8 這 8 個數字,則最小的 4 個數字為 1,2,3 和 4。
代碼思路:方法有很多種,只是時間復雜度問題。
代碼一:快速排序c語言實現
#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");
}
代碼2:最小堆排序算法
#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");
}