Hi, I am

Ngô Tôn

I am a programmer.

Home / Programming / C/C++ / Chỉ ra số hạng lớn thứ k của mảng

Chỉ ra số hạng lớn thứ k của mảng

Yêu cầu:

Cho mảng các số nguyên A gồm n phần tử (n ≤ 30000) và số dương k (k ≤ n). Hãy chỉ ra số hạng lớn thứ k của mảng.

Ví dụ: Mảng A: 6 3 1 10 11 18
Nếu:
k = 1 => Kết quả: 18
k = 2 => Kết quả: 11
k = 3 => Kết quả: 10


Thuật toán:

Để giải quyết bài này, đầu tiên chúng ta dùng phương pháp sắp xếp mảng theo thứ tự giảm dần. Sau đó đếm từ trái sang phải sẽ tìm được số hạng lớn thứ k.

Code:

/************************************************************
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"

bool find_kest_element(int A[], int n, int k, int *res);
void sort_arr_in_descen(int A[], int n);
void print_arr(int A[], int n);

void main( void )
{
int A[] = {1, -2, 5, 6, 8, 13, 4, 10, 27, 90, 32, 59, 76, 76, 77, 98, -90};
int len = sizeof(A)/sizeof(int);
int k = 5;
int res;
sort_arr_in_descen(A, len);
print_arr(A, len);
if(find_kest_element(A, len, k, &res) == false)
{
printf("\nNot found k(th) largest element");
getch();
exit(0);
}
printf("\nThe %dth largest element in array is: %d", k, res);

getch();
}

//Find k(th) largest element.
bool find_kest_element(int A[], int n, int k, int *res)
{
int i;
int kest_pos;
int temp = A[0];
if(k <= 0 || k > n)
return false;
for(kest_pos = 1,i = 1; i < n; i++)
{
if(temp > A[i])
{
temp = A[i];
kest_pos++;
}
if(kest_pos == k)
{
*res = temp;
return true;
}
}
return false;
}

//Sort text in ascending
void sort_arr_in_descen(int A[], int n)
{
int i, j;
int tem;
for(i = 0; i < n - 1; i++)
for(j = i+1; j < n; j++)
{
if(A[i] < A[j])
{
tem = A[i];
A[i] = A[j];
A[j] = tem;
}
}
}

//Display array
void print_arr(int A[], int n)
{
int i;
printf("\n=============================");
for(i = 0; i < n; i++)
{
printf("\nA[%d] = %d", i, A[i]);
}
}

Kết quả:

About ngoton

Ngô Tôn is a programmer with passion for tailored software solutions. Comes with 7+ years of IT experience, to execute beautiful front-end experiences with secure and robust back-end solutions.

Check Also

Xây dựng hàm bạn để tính diện tích hình chữ nhật

Yêu cầu: Xây dựng hàm bạn để tính diện tích hình chữ nhật Code: Giải …

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
https://partyshuttlepty.polyvore.com/ Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
https://partyshuttlepty.polyvore.com/
Guest

Hi to all, the contents present at this web site are actually awesome for people knowledge, well, keep up the good work
fellows.