Ejemplo n.º 1
0
 // use max priority queue of size k
 // since insert/delete are O(lg k), time complexity O(N lg k)
 public static int KthSmallest(int[] a, int k)
 {
     MaxPQ pq = new MaxPQ(k);
     for (int i = 0; i < a.Length; i++)
     {
         if (i < k)
             pq.Insert(a[i]);
         else
             if (pq.GetMax() > a[i])
             {
                 pq.DeleteMax();
                 pq.Insert(a[i]);
             }
     }
     return pq.GetMax();
 }
Ejemplo n.º 2
0
        // use max priority queue of size k
        // since insert/delete are O(lg k), time complexity O(N lg k)
        public static int KthSmallest(int[] a, int k)
        {
            MaxPQ pq = new MaxPQ(k);

            for (int i = 0; i < a.Length; i++)
            {
                if (i < k)
                {
                    pq.Insert(a[i]);
                }
                else
                if (pq.GetMax() > a[i])
                {
                    pq.DeleteMax();
                    pq.Insert(a[i]);
                }
            }
            return(pq.GetMax());
        }
Ejemplo n.º 3
0
        public static void Test()
        {
            int[] array = { 3, 1, 2, 5, 6, 7, 9, 10, 4, 8 };
            MaxPQ pq    = new MaxPQ(array);

            for (int i = 0; i < array.Length; i++)
            {
                Console.Write(pq.DeleteMax() + " "); // 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
            }
            Console.WriteLine();

            pq = new MaxPQ(2);
            for (int i = 0; i < array.Length; i++)
            {
                pq.Insert(array[i]);
            }
            while (pq.Count() > 0)
            {
                Console.Write(pq.DeleteMax() + " "); // 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
            }
            Console.WriteLine();
        }
Ejemplo n.º 4
0
        public static void Test()
        {
            int[] array = { 3, 1, 2, 5, 6, 7, 9, 10, 4, 8 };
            MaxPQ pq = new MaxPQ(array);
            for (int i = 0; i < array.Length; i++)
                Console.Write(pq.DeleteMax() + " "); // 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
            Console.WriteLine();

            pq = new MaxPQ(2);
            for (int i = 0; i < array.Length; i++)
                pq.Insert(array[i]);
            while (pq.Count() > 0)
                Console.Write(pq.DeleteMax() + " "); // 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
            Console.WriteLine();
        }