On the move:

I'm currently moving the following to their own blogs: Unix, HTML for Blogs, Perl & Java.
The links are on the left side.

Tuesday, October 14, 2008

Java - A Way to Manually Sort an Array


public class mySort
{
public static void main(String[] str)
{
int[] array1 = {53,43,33};
int idx2, idx1, temp;
//----------------------------------------------
// The 1st index is set to 0. On each loop it's
// compared against the length, and incremented.
//----------------------------------------------
for (idx1 = 0; idx1 < array1.length; idx1++)
{
//--------------------------------------------
// The 2nd index is set to 1 position higher
// than the 1st. On each loop it's compared
// against the length, and incremented.
//--------------------------------------------
for (idx2 = idx1 +1; idx2 < array1.length; idx2++)
{
//------------------------------------------
// If the 1st number is greater than the 2nd
// number, the two numbers switch. The 2nd
// has to be stored so it's not overwritten.
//------------------------------------------
if (array1[idx1] > array1[idx2])
{
temp = array1[idx2];
array1[idx2] = array1[idx1];
array1[idx1] = temp;
}
}
}
//----------------------------------------
// display data when the sort is done
//----------------------------------------
for (idx1 = 0; idx1 < array1.length; idx1++)
{
System.out.printf("Final: array1(%d)= %d\n", idx1, array1[idx1]);
}
}
}

No comments:

Post a Comment