-2

I am making a selection sort algorithm in Java.

The logic seems to be perfect, but this code is not sorting the elements.

import java.util.Arrays;
public class selectionsort{

    int y;


    void swap(int a[], int firstindex, int secondindex){
        int temp=a[firstindex];
        a[firstindex]=a[secondindex];
        a[secondindex]=temp;

    }

    public void selectionsort1(int a[],int i){
       int lowestindex;
       for(y=0;y<a.length-2;y++){
           lowestindex=selectionsort2(a,y);
           swap(a,y,lowestindex);
       }

    }

    public int selectionsort2(int a[],int y){
        int setvalue=a[y];
        int setindex=y;
        for(int x=setindex+1;x<a.length;x++){
            if(a[x]<setvalue){
                setvalue=a[x];

            }

        }
        return setvalue;
    }

    public static void main(String args[]){
        int[] a={88,28,39,40,15,06,97,80};
        int i=0;
        int y=0;
        selectionsort s1=new selectionsort();
        s1.selectionsort1( a, i);
        for (int element: a) {
            System.out.println(element);
        }
    }


}

Why doesn't this work?

1

2 Answers 2

0

Why has your algorithm a state? (attribute y). You should be able to implement an algorithm of that kind purely with static methods. No need to create a "sorting object".

Selection sort: this algorithm does not show any need of nested method calls. Please check the algorithm before implementing: https://en.wikipedia.org/wiki/Selection_sort. Just run over your elements over and over again as shown on that page's animation.

Please also note that this algorithm is highly inefficient for large arrays and may lead to terrible computation times (combined with your nested calls, it would also lead to terrible memory consumption). If your question is not academic, but a practical one - and you "only" need to sort an array, you might very well just use Java's "Arrays.sort()" method.

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

Comments

-2

Java passes method arguments as copies of original references. You can modify them and they will show up to be changed but a swap will fail. You can return the array and catch it from there to prjnt the modified array.

This article gives more insight regarding this https://www.javaworld.com/article/2077424/learn-java/does-java-pass-by-reference-or-pass-by-value.html

Hope this helps.

1 Comment

I don't see a problem with this swap() method. The reference to the array is a copy - yes, but you will still be working on one array only - and this array's elements will actually be modified / swapped.

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.