Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please Help Trying to sort array Java

Tags:

java

arrays

  public class selectionsorter
  {
public selectionsorter(int[] x)
{
    theArray=x;
}
public void sort()
{
    for(int i=0; i<theArray.length-1;i++)
    {
        start=i;
        findMinPos();
    }
}
public void findMinPos()
{
    int minpos=start;
    for(int i=0;i<theArray.length;i++)
    {
        if(i>start)
        {
        if(theArray[i]<theArray[start])
        {
        start=i;
        }
        }
    }
    swap();
}
public void swap()
{
    temp=theArray[start];
    theArray[start]=theArray[minpos];
    theArray[minpos]=temp;
}
private int[] theArray;
private int minpos;
private int start;
private int temp;
   }

Tester File

   public class selectionsortertester
  {
public static void main(String[] args)
{
    int[] x ={3,7,5,6,9,2};
    selectionsorter y=new selectionsorter(x);

    y.sort();
    for(int i=0; i<x.length;i++)
    System.out.print(x[i]+" ");
}
  }

I want it to sort the array it from lowest to highest and it does the first number, and the output is "2 7 5 6 9 3" Please Help and Thanks Does anyone know why it is doing this and how I can fix it, Thanks

like image 712
user3014333 Avatar asked Jun 25 '26 23:06

user3014333


1 Answers

You can do it this way

Arrays.sort(x);

See docs here.

like image 178
Alex Avatar answered Jun 27 '26 13:06

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!