C# program to find K’th smallest element in a 2D array


Declare a 2D array −

int[] a = new int[] {
   65,
   45,
   32,
   97,
   23,
   75,
   59
};

Let’s say you want the Kth smallest i.e, 5th smallest integer. Sort the array first −

Array.Sort(a);

To get the 5th smallest element −

a[k - 1];

Let us see the complete code −

Example

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]);
      }
   }
}

Updated on: 22-Jun-2020

339 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements