简体   繁体   中英

Insert sorting strings from an array in alphabetical order

I am really not 100% sure how to insert sort alphabetically from an array. This is what I have so far and any help is appreciated.

I am trying to use the insert sort algorithm to sort alphabetically in this project.

I am getting some errors in sorting, as well as runtime errors.

Thanks!

// The "Insertion_Sort_Example" class.
import java.awt.*;
import java.io.*;
import java.util.*;

public class SortPlanets
{





    public static void main (int [] args)
    {
    String Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto ;
    String list [] = {Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto};   // Array holding contents

    System.out.println ("Array contents before sorting...");  // simple print statements to show proof of before sort
    for(int i = 0; i < 5; i++) {
        System.out.println(list[i]);
    }

    System.out.println ("");
    System.out.println ("************************************");

    insertSort (list);   // call to insert function

    System.out.println ("************************************");   // insert after
    System.out.println ("Array contents after sorting...");
    for(int i = 0; i < 5; i++) {
        System.out.println(list[i]);
    }

    // Place your program here.  'c' is the output console
    } // main method


    public static void insertSort (String [] list)  // sort function
    {
    for (int top = 1 ; top < list.length ; top++)
    {
        int item = list [top];
        int i = top;
        while (i > 0 && item < list [i - 1])
        {
          list [i] = list [i - 1];
          i--;
        }
        list [i] = item;
        System.out.print (list [0]);
        System.out.print (" ");
        System.out.print (list [1]);
        System.out.print (" ");
        System.out.print (list [2]);
        System.out.print (" ");
        System.out.print (list [3]);
        System.out.print (" ");
        System.out.print (list [4]);
        System.out.println ();
    }
    }
} // Insertion_Sort_Example class
java.util.Collections.sort(list);

This will put the list in alphabetical order

EDIT: Atish has the more complete answer

String list [] = {Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto};

Sort your list list using java.util.Collections method

java.util.Collections.sort(list);

sort() api sort the array in Natural Ordering (sort alphabetically) .

I just cleaned up your code so that it works -- here you go:

A few things I noticed -- When you initialize your planets -- make sure that you initialize them so they are not all null eg String Earth = "Earth", not just String Earth. When you compare strings in your sort - make sure you use .compareTo() method. You cannot use < or > to compare String objects. Other than that you were kinda close. GJ mate.

package com.cudp.cuprodigy.utils;

import java.awt.*;
import java.io.*;
import java.util.*;

public class SortPlanets
{





    public static void main (String [] args)
    {
        String Mercury="Mercury", Venus="Venus", Earth="Earth", Mars="Mars", Jupiter="Jupiter", Saturn="Saturn", Uranus="Uranus", Neptune="Neptune", Pluto="Pluto" ;
        String list [] = {Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto};

        System.out.println ("Array contents before sorting...");
        System.out.print (list [0]);
        System.out.print (" ");
        System.out.print (list [1]);
        System.out.print (" ");
        System.out.print (list [2]);
        System.out.print (" ");
        System.out.print (list [3]);
        System.out.print (" ");
        System.out.print (list [4]);
        System.out.println ("");
        System.out.println ("************************************");
        System.out.println ("PLEASE. NOT THE ASS.");

        SortPlanets.insertSort (list);

        System.out.println ("************************************");
        System.out.println ("Array contents after sorting...");
        System.out.print (list [0]);
        System.out.print (" ");
        System.out.print (list [1]);
        System.out.print (" ");
        System.out.print (list [2]);
        System.out.print (" ");
        System.out.print (list [3]);
        System.out.print (" ");
        System.out.print (list [4]);





        // Place your program here.  'c' is the output console
    } // main method


    public static void insertSort (String [] list)
    {
        for (int top = 1 ; top < list.length ; top++)
        {
            String item = list [top];
            int i = top;
            while (i > 0 && item.compareTo(list [i - 1]) < 0)
            {
                list [i] = list [i - 1];
                i--;
            }
            list [i] = item;
            System.out.print (list [0]);
            System.out.print (" ");
            System.out.print (list [1]);
            System.out.print (" ");
            System.out.print (list [2]);
            System.out.print (" ");
            System.out.print (list [3]);
            System.out.print (" ");
            System.out.print (list [4]);
            System.out.println ();
        }
    }
} // Insertion_Sort_Example class

Try Below code:

import java.util.Arrays;
    public class Mainclass {        
        public static void main(String[] args) {
            String list [] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
            Arrays.sort(list);
            for(String str:list)
                System.out.println(str);    

        }   
    }

I believe that the answer from atish is good and easy to understand. But, there is an alternative if you can consider using the Java libraries for sorting.

Java 8 introduces the stream APIs that has natural built in sorting. The sorted -method can be invoked as seen below or by providing a custom Comparator .

// Array of planet names (is Pluto technically a planet?)
String[] planets = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};

// Java 8 Streams are used here to do the sorting and iterations
String[] sortedPlanets = Arrays.stream(planets) // Create the stream
                               .sorted() // Sort the stream
                               .toArray(String[]::new); // Convert back to String[]

System.out.println(Arrays.toString(planets)); // order from the sun
System.out.println(Arrays.toString(sortedPlanets)); order alphabetically

Just a few lines of streaming Java 8 code does the trick!

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