0

I was debugging my code and found a problem with my Selection Sort Algorithm.

The code below almost sorts it, but I cant understand why all of it is not sorted. have tried everything but to no avail.

import java.util.Random;


public class Help
{
    //private static int[] myarray=new int[20];
    private static int[] array;
    public static void main(String[] args)
    {
       array=new int[20];
        fillArrayRandom(array);

        sortAscending(array);

        ///This is the bit that does not do what it is meant to do!
        for(int i=0;i<array.length;i++)
        {
           // System.out.printf("Testing %d%n",myarray[i]);
        }

    }
    public static void fillArrayRandom(int[] array)
    {
        int i;
        for(i=0;i<array.length;i++)
        {
            array[i]=getRandomNum();
        }
    }

    public static int getRandomNum()``
    {
        Random num=new Random();
        int TestNumber=num.nextInt(2000);
        return TestNumber;
    }

    public static void sortAscending(int[] array)
    {
        int smallest;


        for(int i=0;i<array.length-1;i++)
        {
            smallest=i;

            for(int index=i+1;index<array.length;index++)
            {
                if(array[index]<array[smallest])
                    smallest =index;


               swap(i,smallest);
            }

            System.out.printf("%d%n",array[i]);

        }

    }

    public static void swap(int first,int second)
    {
        int temporary=array[first];
        array[first]=array[second];
        array[second]=temporary;
}
}
3
  • Is that homework? Show expected output vs. real. Commented Apr 20, 2014 at 17:58
  • The loop that "doesn't do what it's meant to do" has no uncommented code inside. Commented Apr 20, 2014 at 17:58
  • The ouput is that it is supposed to output the numbers in ascending order. It is ok as Ted solved my problem. But thank you very much for the respones and thank you Ted for helping me. Commented Apr 20, 2014 at 18:04

1 Answer 1

1

You need to swap after the inner loop has completed:

public static void sortAscending(int[] array)
{
    int smallest;


    for(int i=0;i<array.length-1;i++)
    {
        smallest=i;

        for(int index=i+1;index<array.length;index++)
        {
            if(array[index]<array[smallest])
                smallest =index;


        }
        if (i != smallest) swap(i,smallest);

        System.out.printf("%d%n",array[i]);

    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.