hi..
I am writing the code for selection sort, you'll need to pass the numbers for sorting as command line arguments that is along with the command you use to run the java program
e.g., java Selection 12,45,1,76,50
the code is as follows:
class Selection
{
public static void main(String arg[])
{
int x[]; //declaring an empty array,initialized later
int i;
//checking if arguments have been given or not at the command line
if(arg.length==0)
System.out.println("No Arguments Specified...\n");//prints msg if no args specified
else
{
x=new int[arg.lenght]; //initializing the array with the no. of args specified.
try //trapping any errors that might occur
{
for(i=0;i<x.length;i++) //loop for putting the values into the array
x[i]=Integer.parseInt(arg[i]);
selectionSort(x); //calling the method for sorting,defined later in the class
//printing the sorted list
System.out.println("Sorted List:-");
for(i=0;i<x.length;i++)
System.out.println(x[i]);
}
catch(NumberFormatException E) //traps the error if specified arg is not a number
{
System.out.println("Given argument is not a number...\n");
}
}
}
static void selectionSort(int x[]) //method for sorting the list,made static for using in main
{
int i,j;
int pos=0; //variable to fix a position in array
int min=0; //variable to fix a number as minimum.
for(i=0;i<x.length-1;i++)
{
min=x[i+1]; //setting the minimum number
pos=i+1; //fixing the position to the index of that number
for(j=i+1;j<x.length;j++)
{
if(min>x[j]) //if number at x[j] is graeter than minimum then
{
min=x[j]; //put x[j] in min
pos=j; //and change position to index number of j
}
}
if(x[pos]<x[i]) //if number at x[pos] is less than number at x[i] then swap the values
{
x[pos]=x[pos]+x[i];
x[i]=x[pos]-x[i];
x[pos]=x[pos]-x[i];
}
}
}
}
hope this code will help you..
we do not need to create to separate classes for sorting a list here.
NICE WORK!!! You did his homework for him!!!!
Reputation Points: 113
Solved Threads: 19
Postaholic
Offline 2,108 posts
since Jun 2004