Tìm số nhỏ thứ k trong mảng, đọc từ File

on Monday, March 2, 2015
Tìm số nhỏ thứ k trong mảng, đọc từ File . Ví dụ:
INPUT.inp
5 3
3 4 5 7 1
OUTPUT.out
4



#include< iostream>
#include< iomanip>
#include< fstream>
using namespace std;

void HoanVi(int &, int &);
void Bubble_sort(int[], int);
int TimSoNhoThuk(int [], int , int , int *);

void HoanVi(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
void Bubble_sort(int a[], int n){
for (int i = n - 1; i >= 0; i--){
for (int j = 0; j < i; j++){
if (a[j]>a[j + 1])
HoanVi(a[j], a[j + 1]);
}
}
}
int TimSoNhoThuk(int a[], int n, int k, int *res){
int temp = a[0], pos = 0;
if (k >= n||k < 0)
return 0;
for (int i = 0; i < n; i++){
if (a[i] < a[i + 1]){
temp = a[i];
pos++;
}

if (k == pos){
*res = temp;
return 1;
}
}
return 0;
}

int main(){
int n,k,res,*a;

ifstream FileIn;
FileIn.open("INPUT.inp", ios_base::in); // Mở file để đọc.

// Kiểm tra xem File có tồn tại hay không ?
if (!FileIn)
{
cout << "\nKhong tim thay tap tin INPUT.inp \n";
system("pause");
exit(0);
}
FileIn >> n >> k;
a = new int[n];
for (int i = 0; i FileIn >> a[i];
FileIn.close();

Bubble_sort(a, n);
if (TimSoNhoThuk(a, n, k, &res) == 0){
cout << "\n Khong ton tai ";
}
else cout << "So nho thu " << k << " la : " << res<<"\n";
ofstream FileOut;
FileOut.open("OUTPUT.out", ios_base::out);
FileOut << res;
FileOut.close();
system("pause");
return(0);
}

0 comments:

Post a Comment