For example, we have the following array:
char data[]=new char[]{'A','S','O','R','T','I','N','G','E','X','A','M','P','L','E'};
and an index array:
int a[]=new int[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14};
void insitu (char data[], int a[], N)
{
for (int i=0;i<N;i++)
{
char v=data[i];
int j, int k;
for (k = i; a[k] != i; k = a[j], a[j]=j)
{
j=k;
data[k]=data[a[k];
}
data[k]=v;
a[k]=k;
}
}
My question is what j should be initialized to. When I run this code, it asks me to initialize j; what should I do?
This is a Java implementation of the in-place sort in Sedgewick’s Algorithms in C++ (see page):
On array declarations
Please, please, do not make a habit of declaring arrays like this:
You should instead put the brackets with the type, rather than with the identifier:
Related questions
Object[] xandObject x[]?int[] myArrayandint myArray[]in Javaint[] k,iandint k[],ii!On definite assignment
The compiler is smart enough to know when a local variable is definitely assigned, taking into account loop constructs, etc.
The following code compiles:
While this doesn’t:
Similarly, this compiles:
This is because of the semantics of
forloop, where the loop body (local = 0;) precedes the loop update (local++) in the control flow, even though it may not look like it in the text.The specification doesn’t allow the compiler to be too smart; for example the following doesn’t compile:
But this does:
See also