Saturday, August 8, 2009

Math 128 - Algorithm

Problem: Find the smallest and the second smallest element in the sequence (s1,s2,...sn).

This is my java code for our assignment last time in Math 128.
Note: This code will only work in Sorted values in the sequence.
For example:

1 2 3 4 5 6 7 8 9 10
or
4 3 2 1



import java.util.*;
public class mi{
public static void main(String[]args){
Scanner scan = new Scanner (System.in);


System.out.print("How many numbers in the sequence? ");
int n=scan.nextInt();
int a[]=new int [n];
System.out.println();
System.out.println("*********************************");
System.out.println();


for (int x=0;xsmall2)
{
small=small2;
small2=a[y];
}
else if (smallsmall && small
{
small=small;
small2=small2;
}

}
System.out.println();
System.out.println("*********************************");
System.out.println();
System.out.println("The smallest value in the sequence is "+ small);
System.out.println("The second smallest value is " + small2);

}
}



If you want a better java program code or idea about this, you can also ask Mr. Joel "Pare" Benaldo also known as MaCuBeX.




Joel Benaldo



No comments:

Post a Comment