Search code examples
javaselection-sort

Selection sort issues


Feel as if im so close, just dont know what to put in "If Statment" and order of things. Please Help. Also not sure what to do with swap method for sure?

private static void selectionSort(String[] words, int numWords)
{
     for (int i = 0; i < words.length; i++)  
    {
        int min = i;
        for(int j = i+1; j < words.length; j++)
        {
            if(words[index]<words[minIndex])
            {
                min = j;
            }

        swap(words, i, j);
        }
    } 
}

public static int indexOfNextSmallest(String[] words, int startIndex) 
{
    int minIndex = startIndex;

    for(int i = startIndex; i < words.length; i++) {
        if(words[i].compareTo(words[minIndex]) < 0)
            minIndex = i;
    }
    return minIndex;
}

private static void swap(String[] words, int i, int j)
{
    String swap = words[i];
    words[i] = words[j];
    words[j] = swap;
}

Trying to add user validation. Wondering if I should do it in method below or up in main method?

private static int getMenuChoice(Scanner stdIn)
{
    int option = 0;

    System.out.println("\n1:  Add Word");
    System.out.println("2:  Remove Word");
    System.out.println("3:  Print Words");
    System.out.println("4:  Quit");
    System.out.print("Choose an option(1-4): ");
    option = stdIn.nextInt();

    return option;
}

Solution

  • You are trying to compare 2 strings using '<' operator which doesnt work. Rather you should use compareTo function to compare 2 objects that are Comparable.

       if(words[index]<words[minIndex])   // doesnt work - Compilation error
       {
                min = j;
       }
    

    Change your if condition in the method selectionSort as follows :

        if(words[j].comapareTo(words[min]) < 0)
        {
                min = j;
        }
    

    Also you need to swap words at index i & min, rather than swapping i & j

      swap(words, i, j);  //wrong
    
      swap(words, i, min); //correct -  as it swaps min word & current word