Hi everyone,

Just need abit of help. im studying selection sorting at the mo.....ive wrote an essay wot it and how it works but im tryin to an example in java and im having problems with that.....im not a very good java user.....ive only just started.

i just wanted to know do u or would it be best to use 2 differnt classes - one for the sorting and one to enter the numbers u want sorting?

also if u were 2 use 2 differnt classes how would u connect the 2 together?

Thanks

Dani AI

Generated

— short practical answer: a single class is perfectly fine for learning, but extracting the sort into its own method or a small utility class makes the code cleaner and reusable. was right that input can be handled in main and the sorting can be a callable method; ’s suggestion to use separate functions (methods) is the same design idea without extra classes.

Several posts show common mistakes worth calling out. ’s example contains typos and logic errors: arg.lenght should be arg.length; parsing must use Integer.parseInt(arg[i]); initializing the candidate minimum as x[i+1] skips the current element; and swapping with arithmetic is fragile and can overflow — use a temporary variable. Also command-line arguments are space-separated (java Selection 12 45 1 76 50) unless a single comma-separated string is explicitly split. ’s use of Arrays.sort is fine for production, but it does not illustrate the selection-sort algorithm.

A compact, correct example that reads a line of numbers from standard input, parses them, runs selection sort, and prints the result:

import java.util.*;

public class SelectionSortDemo {
  public static void selectionSort(int[] a) {
    for (int i = 0; i < a.length - 1; i++) {
      int minIdx = i;
      for (int j = i + 1; j < a.length; j++) {
        if (a[j] < a[minIdx]) minIdx = j;
      }
      if (minIdx != i) {
        int tmp = a[i];
        a[i] = a[minIdx];
        a[minIdx] = tmp;
      }
    }
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String line = sc.nextLine();
    String[] toks = line.trim().split("\\s+");
    int[] arr = new int[toks.length];
    for (int i = 0; i < toks.length; i++) arr[i] = Integer.parseInt(toks[i]);
    selectionSort(arr);
    System.out.println(Arrays.toString(arr));
  }
}

Troubleshooting tips: catch NumberFormatException around parsing, handle empty input, and test small arrays and edge cases (0 or 1 element). Selection sort does O(n^2) comparisons and O(n) swaps; for large inputs prefer built-in sorts (Arrays.sort). The thread’s code samples are useful learning points — fixing the typos and using a temp variable for swaps will make the algorithm correct and easy to follow.

Recommended Answers

All 9 Replies

Actually, you could probably use


public static void main (String[] main) {

Initialize your class
Write a loop to get your numbers
send to method in that classs

}

So, your answer is. You don't have to use two classes. In fact, just one for your selection sort and have the user input numbers in the public static void part.

-Tino

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=Integer.parseInt(arg);


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);
}
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)   //if number at x[pos] is less than number at x then swap the values
{
x[pos]=x[pos]+x;
x=x[pos]-x;
x[pos]=x[pos]-x;
}
}
}
}

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!!!!

hii
try to use two function rather tha two class

import java.util.*;
public class DS2
{
    public static void main(String[] args)
    {   
        Scanner k=new Scanner(System.in);
        int[] ds=new int[10];
        for (int z=0;z<10;z++)
        {
            Random R=new Random();
            int x=R.nextInt(999)+1;
            ds[z]=x;
        }
        System.out.println("Numbers Before Sort:\n"+ds[1]+","+ds[2]+","+ds[3]+","+ds[4]+","+ds[5]+","+ds[6]+","+ds[7]+","+ds[8]+","+ds[9]+"\n");
        Arrays.sort(ds);
        System.out.print("Numbers After Sort:\n"+ds[1]+","+ds[2]+","+ds[3]+","+ds[4]+","+ds[5]+","+ds[6]+","+ds[7]+","+ds[8]+","+ds[9]);
}       
}
commented: Thanls for dragging up an ancient thread to post a useless piece of code. -2

hai..pwedi nyo b akong bgyan ng isang code about selection sort....thanks

hai..pwedi nyo b akong bgyan ng isang code about selection sort....thanks

Start a new thread and write proper english

can you gave us a running program about selection sort that the user will input something from the keyboard...thank you...

can you gave us a running program about selection sort that the user will input something from the keyboard...thank you...

NO.

Start a new thread. There are plenty of examples on how to read input with the Scanner class. Start a new thread with some code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.