简体   繁体   中英

How to make a selection sort algorithm using Java collection linkedlist?

I'm new to Java and I need to make a selection sort algorithm using Java LinkedList. I tried making the insertion sort, but I can't turn it into a selection sort. This is my selection sort code:

import java.util.*;
public class select {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        LinkedList<Integer> data = new LinkedList<>();

        System.out.println("Enter total count of elements-> ");
        int num = input.nextInt();

        while(num>0){
            data.add(input.nextInt());
            num--;
        }

        System.out.println("Original data:\n" +data);

        LinkedList<Integer> sortedData=sort(data);
        System.out.println("Sorted data:\n"+sortedData);
    }
    
    public static LinkedList<Integer> sort(LinkedList<Integer> data) {
        
        ListIterator<Integer> iterator=data.listIterator();
        while (iterator.hasNext()) {
            int key=iterator.next();
            

            for(int i = 0 ;i<data.size()-1;i++) {
                for(int j = i+1; j < data.size(); j++){
                    if(data.get(j) < key){
                        int x = data.get(j);
                        int y = key;
                        swap(data, x, y);
                    }
                }
                
            }
        }
        return data;
    }

    private static void swap(LinkedList<Integer> data, int x, int y) {
        int index1 = data.indexOf(x);
        int index2 = data.indexOf(y);

        if(index1 == -1 || index2== -2){
            return;
        }
    }
}

The sorted data is always the same as the original data and I don't know which went wrong.

The problem seems to be that your swap method doesn't actually swap the values.

These two lines will get the indices of your data, as you'd expect.

int index1 = data.indexOf(x);
int index2 = data.indexOf(y);

But all this does is ensure that your indices are valid, meaning the data were found. (Although the second check should also be -1 because the #indexOf method always returns the index, if found, or -1. Never -2.)

if (index1 == -1 || index2 == -1){ // changed to -1 on both
    return;
}

To actually do the swap, you need something like at the end of the other code in your swap method:

data.set(index1, y);
data.set(index2, x);

The #set method changes the value at the first argument index to the value in the second argument, so doing it twice will effectively swap the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM