-
Notifications
You must be signed in to change notification settings - Fork 0
/
kth-largest-smallest.cs
56 lines (39 loc) · 1.35 KB
/
kth-largest-smallest.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
// To execute C#, please define "static void Main" on a class
// named Solution.
class Solution
{
static void Main(string[] args)
{
int[] arr = new int[4]{1,7,3,5}; //1,3,5,7
int k = 2;
kthLargest(arr, k);
kthSmallest(arr, k);
}
public static void kthSmallest(int[] arr, int k)
{
int length = arr.Length;
if(k >= length)
{
Console.WriteLine("the position is outside the bounds of the array");
return;
}
Array.Sort(arr); //sort the array in ascending order, O(nlogn)
int kthSmallest = arr[k-1];
Console.WriteLine(k + "th smallest: " + kthSmallest);
}
public static void kthLargest(int[] arr, int k)
{
int length = arr.Length;
int lastIndex = length -1;
if(k >= length)
{
Console.WriteLine("the position is outside the bounds of the array");
return;
}
Array.Sort(arr); //sort the array in ascending order, O(nlogn); 1,3,5,7
Array.Reverse(arr); //1,3,5,7; sort the array in descending order; 7,5,3,1
int kthLargest = arr[k-1];
Console.WriteLine(k + "th largest: " + kthLargest);
}
}