# 剑指OFFER之最小的K个数（九度OJ1371）

## 题目描述：

```8 4
4 5 1 6 2 7 3 8```

`1 2 3 4`

## 解题思路：

我们通过快排找到第k个数，然后比他的小的都在左边，比他大的都在右边

```void getNumber(int n,int m){
int i;
int begin = 0;
int end = n-1;
int index = patition(begin,end);
while(index != m-1){
if(index > m-1){
end = index -1;
index = patition(begin,end);
}else{
begin = index+1;
index = patition(begin,end);
}
}
}```

在进行一次快排，将数组有序的输出。

```void Qsort(int begin,int end){
if(begin >= end)
return ;
else{
int middle = patition(begin,end);
Qsort(begin,middle-1);
Qsort(middle+1,end);
}
}```

快排的代码如下：

```int patition(int begin,int end){
int index,small;
small = begin-1;
for(index = begin;index < end;index++){
if(gArr[index] < gArr[end]){
small++;
if(small != index)
swap(index,small);
}
}
small++;
swap(small,end);
return small;
}
void swap(int i,int j){
int tmp = gArr[j];
gArr[j] = gArr[i];
gArr[i] = tmp;
}```

## 全部代码：

```#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 200000
int  gArr[MAXSIZE]={0};
void getNumber(int n,int m);
void Qsort(int begin,int end);
int patition(int begin,int end);
void swap(int i,int j);
int main(){
int n,m,i;
while(scanf("%d %d",&n,&m)!=EOF && n>=1 && n<=200000){
for(i=0;i<n;i++)
scanf("%d",&gArr[i]);
getNumber(n,m);
Qsort(0,m-1);
for(i=0;i<m-1;i++){
printf("%d ",gArr[i]);
}
printf("%d\n",gArr[m-1]);
}
return 0;
}
void Qsort(int begin,int end){
if(begin >= end)
return ;
else{
int middle = patition(begin,end);
Qsort(begin,middle-1);
Qsort(middle+1,end);
}
}
void getNumber(int n,int m){
int i;
int begin = 0;
int end = n-1;
int index = patition(begin,end);
while(index != m-1){
if(index > m-1){
end = index -1;
index = patition(begin,end);
}else{
begin = index+1;
index = patition(begin,end);
}
}
}
int patition(int begin,int end){
int index,small;
small = begin-1;
for(index = begin;index < end;index++){
if(gArr[index] < gArr[end]){
small++;
if(small != index)
swap(index,small);
}
}
small++;
swap(small,end);
return small;
}
void swap(int i,int j){
int tmp = gArr[j];
gArr[j] = gArr[i];
gArr[i] = tmp;
}
/**************************************************************
Problem: 1371
User: xhalo
Language: C
Result: Accepted
Time:950 ms
Memory:1696 kb
****************************************************************/```

797 篇文章74 人订阅

0 条评论

## 相关文章

4297

792

1133

1223

2827

4259

### Effective Modern C++翻译(1)：序言

/*********************************************************** 关于书： 书是我从网上找到的effec...

1969

3857

4312

3206