What is Recursion?
Recursion is a programming technique that allows the programmer to express operations in terms of themselves. In Java, C, C++ and some more programming languages, this takes the form of a function that calls itself.
A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to “repeat the process”. This makes it sound very similar to a loop because it repeats the same code, and in some ways it is similar to looping. On the other hand, recursion makes it easier to express ideas in which the result of the recursive call is necessary to complete the task. Of course, it must be possible for the “process” to sometimes be completed without the recursive call.
One simple example is the idea of building a wall that is ten feet high; if I want to build a ten foot high wall, then I will first build a 9 foot high wall, and then add an extra foot of bricks. Conceptually, this is like saying the “build wall” function takes a height and if that height is greater than one, first calls itself to build a lower wall, and then adds one a foot of bricks.
import java.io.*;
public class Sorter
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String nam[];
int N, pos;
Sorter()
{
N=0;
pos=0;
nam = null;
}
Sorter(int nx)
{
N=nx;
nam = new String[N];
pos=-1;
}
void readNames()throws IOException
{
int i;
System.out.println("Enter "+N+" names for the array:");
for(i=0;i<n;i++)
{
nam[i] = br.readLine();
}
}
void show()
{
int i;
System.out.println("The names in the array:");
for(i=0;i<n;i++) { System.out.println(nam[i]); } } void findmin(int j, String min) { if(j==N) return; if(min.length()>nam[j].length())
{
min = nam[j];
pos = j;
}
findmin(j+1,min);
}
void SortNames(int i)
{
if(i==N)
return;
String min = nam[i];
pos = i;
findmin(i+1, min);
String tmp = nam[i];
nam[i] = nam[pos];
nam[pos] = tmp;
SortNames(i+1);
}
public static void main()throws IOException
{
int size;
System.out.println("Enter the size:");
size = Integer.parseInt(br.readLine());
Sorter nxt = new Sorter(size);
nxt.readNames();
nxt.show();
nxt.SortNames(0);
nxt.show();
}
}