Khai báo mảng 2D -
int[] a = new int[] {
65,
45,
32,
97,
23,
75,
59
}; Giả sử bạn muốn số nguyên nhỏ nhất thứ K, tức là số nguyên nhỏ nhất thứ 5. Sắp xếp mảng trước -
Array.Sort(a);
Để lấy phần tử nhỏ thứ 5 -
a[k - 1];
Hãy cho chúng tôi xem mã hoàn chỉnh -
Ví dụ
using System;
using System.IO;
using System.CodeDom.Compiler;
namespace Program {
class Demo {
static void Main(string[] args) {
int[] a = new int[] {
65,
45,
32,
97,
23,
75,
59
};
// kth smallest element
int k = 5;
Array.Sort(a);
Console.WriteLine("Sorted Array...");
for (int i = 0; i < a.Length; i++) {
Console.WriteLine(a[i]);
}
Console.Write("The " + k + "th smallest element = ");
Console.WriteLine(a[k - 1]);
}
}
}