#include<iostream>
#include<algorithm>
using namespace std;
bool compare(int a, int b);
int main()
{
int n, k;
cin >> n >> k;
if(n <= 0 || n < k)
return 0;
int *num = new int[n];
for(int i = 0; i < n; i++)
cin >> num[i];
sort(num, num+n, compare);
for(int i = 0; i < k ; i++)
cout << num[i] << endl;
delete [] num;
}
bool compare(int a, int b)
{
return a < b; //升序排列,如果改为return a>b,则为降序
}
method 2:结合快排的方法
#include<iostream>
#include<algorithm>
using namespace std;
int qsort(int[], int, int, int);
int partion(int[], int, int);
int main()
{
int n, k;
cin >> n >> k;
if(n <= 0 || n < k)
return 0;
int *num = new int[n];
for(int i = 0; i < n; i++)
cin >> num[i];
qsort(num, 0, n, k);
for(int i = 0; i < k; i++)
cout << num[i] << endl;
}
int qsort(int num[], int low, int high, int k)
{
int index = partion(num, low, high);
while(index != k-1)
{
if(index > k - 1)
high = index - 1;
else
low = index + 1;
index = partion(num, low, high);
}
}
int partion(int num[], int low, int high)
{
int pivotkey;
pivotkey = num[low];
while(low < high)
{
while(low < high && num[high] >= pivotkey)
high--;
swap(num[low],num[high]);
while(low < high && num[low] <= pivotkey)
low++;
swap(num[low],num[high]);
}
return low;
}
method 3:
结合最小堆,选出最小的k个数(适合k比较小的情况)
结合最大堆,选出(n-k)个最大数,剩下的k个数就是我们需要的(适合k比较大的情况)
下边实现的是最大堆情况:
#include<iostream>
#include<algorithm>
using namespace std;
void heap(int[], int);
void adjHeap(int[], int, int);
int main()
{
int n, k;
cin >> n >> k;
if(n <= 0 || n < k)
return 0;
int *num = new int[n];
for(int i = 0; i < n; i++)
cin >> num[i];
for(int i = (n - 1)/2; i >= 0; i--)
{
adjHeap(num, i, n);
}
for(int i = k; i < n; i++)
{
if(num[0] > num[i])
{
num[0] = num[i];
adjHeap(num, 0, n);
}
}
for(int i = 0; i < k; i++)
cout << num[i] << " ";
}
void adjHeap(int num[], int i, int len)
{
int index = i;
int left = i * 2 + 1; //left = (i<<1) + 1; 算数运算符的优先级要高于位运算符
int right = i * 2 + 2;
if(left < len && num[index] < num[left])
index = left;
if(right < len && num[index] < num[right])
index = right;
if(index != i)
{
swap(num[i], num[index]);
adjHeap(num, index, len);
}
}