Solution:The program uses the concept of partitioning done in quick sort method. In partitioning the list of elements gets divided into
two parts with one part containing all values greater than the pivot element, and second part containing all values smaller the
the pivot element.
Here we take the pivot element as the nth number in the list. As the partitioning progresses, the list gets divided into two parts and we get
the nth smallest element.
Code:
class NthNumber{
public static int searchNthSmallest(int [] iArr, int n)
{
int smallest = iArr[n];
int front = 0;
int rear = iArr.length-1;
while(frontiArr[n-1])
rear--;
if(frontn, then the left partition will contain the solution, else right partition.
This code as keeps on dividing the list into two with only one smaller list to search in next level. So, gives solution in linear time.
___________________________________________________________________________
Problem : Java code to eat up system's memory:
As you all will be familiar with recursive program, in case you are a novice a recursive program is a program that calls itself. For a recursive program to work according to your need, following conditions needs to be fulfilled:
1. A program should have a block of code to call itself.
2. There should be a terminating condition to end the calling cycle.
If in a program first condition is not met, then the program will not be recursive. But if second condition is not met, the program will go in an infinite loop. But what will happen if the program goes in an infinite loop.Well, before that let us discuss what happens when a program gets called. When you call a program, JVM allocates memory in stack for local variables and formal variables. Now if the calling becomes infinite then each time memory will get allocated. If local variables takes huge amount of space then a time will come when stack memory will overflow causing system to hang. Here is a sample code below:
import java.awt.*;
class MemoryOverflow{
Bufferedimage buffImg = new BufferedImage(1000, 500, BufferedImage.TYPE_INT_ARGB)
public static void main(String []args)
{
MemoryOverflow mf = new MemoryOverflow();
mf.recursiveFunction();
}
public recursiveFunction()
{
recursiveFunction();
}
}
___________________________________________________________________________
Java Zone
Problem : Program to find the nth smallest number in linear time :
Subscribe to:
Posts (Atom)
No comments:
Post a Comment