Sorting a vector using the selection sort method

I have to write a program that sorts a Vector using the selection sort algorithm. Unfortunately the textbook only has about 2 pages on vectors so needless to say I'm pretty clueless on how to manipulate vectors. However I think I'm on the right path, however I'm stuck on one part as shown in the code below.     
private static void  selectionSort(Vector parts)
      int index;
        int smallestIndex;
        int minIndex;
        int temp = 0;
        for (index = 0; index < parts.size() - 1; index++)
          smallestIndex = index;
          for (minIndex = index + 1; minIndex < parts.size(); minIndex++)
           if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex))  // this is where I'm having trouble
              smallestIndex = minIndex;
            parts.setElementAt(temp, smallestIndex);
            parts.setElementAt(smallestIndex, index);
            parts.setElementAt(index, temp); if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex))
is returning "ProcessParts3.java:51: operator < cannot be applied to java.lang.Object,java.lang.Object"
Here is the full program:
import java.util.*;
import java.io.*;
public class ProcessParts3
     static Vector parts;
     public static void main(String[] args)
          loadVector();
     private static void loadVector()
     try
          Scanner fileIn = new Scanner(new File("productionParts.txt"));
          parts = new Vector();
          String partIn;
          while (fileIn.hasNext())
               partIn = fileIn.nextLine();
                    parts.addElement(partIn.trim());
          selectionSort(parts);
               for (int i = 0; i < parts.size(); i ++)
               System.out.println(parts.elementAt(i));
     catch(Exception e)
          e.printStackTrace();
     private static void  selectionSort(Vector parts) //from this part down I'm responsible for the coding, everything
                                                           // everything above this was written by the teacher
             int index;
        int smallestIndex;
        int minIndex;
        int temp = 0;
        for (index = 0; index < parts.size() - 1; index++)
            smallestIndex = index;
            for (minIndex = index + 1; minIndex < parts.size(); minIndex++)
                if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex))
                    smallestIndex = minIndex;
            parts.setElementAt(temp, smallestIndex);
            parts.setElementAt(smallestIndex, index);
            parts.setElementAt(index, temp);
}Edited by: SammyP on Nov 27, 2009 11:43 AM

SammyP wrote:
I have to write a program that sorts a Vector using the selection sort algorithm...Hmmm.... Your teacher is, in my humble opinion, a bit of a tard.
1. Vector is basically deprecated in favor of newer implementations of the List interface which where introduced in [the collections framework|http://java.sun.com/docs/books/tutorial/collections/index.html] with Java 1.5 (which became generally available back in May 2004, and went end-of-support Oct 2009). ArrayList is very nearly a "drop in" replacement for Vector, and it is much better designed, and is marginally more efficient, mainly because it is not syncronised, which imposes a small but fundamentally pointless overhead when the collection is not being accessed across multiple threads (as is the case in your program).
2. Use generics. That "raw" Vector (a list of Objects) should be a genericised List<String> (a list of Strings)... because it's compile-time-type-safe... mind you that definately complicates the definition of your static sort method, but there's an example in the link... Tip: temp should be of type T (not int).
Note that String implements [Comparable<String>|http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html], so two String's can safely be compared using the compareTo method... In Java the mathematical operators (<, >, &#43;, -, /, &#42;, etc) are only applicable to the primitive types (byte char, int, float, etc)... The Java Gods just chose to muddy the waters (especially for noobs) by "overloading" the &#43; operator for String (and String only) to enable succinct, convenient string-concatenation... which I personally now see as "a little bit of a mistake" on there part.
     private static void  selectionSort(Vector parts)  {
int index, smallestIndex, minIndex, temp = 0;
for (index = 0; index < parts.size() - 1; index++) {
smallestIndex = index;
for (minIndex = index + 1; minIndex < parts.size(); minIndex++) {
if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex)) {
smallestIndex = minIndex;
parts.setElementAt(temp, smallestIndex);
parts.setElementAt(smallestIndex, index);
parts.setElementAt(index, temp);
}3. ALLWAYS use {curly braces}, even when not strictly necessary for correctness, because (a) they help make your code more readable to humans, and also (b) if you leave them out, you will eventually stuff it up when you insert a line in the expectation that it will be part of the if statement (for example) but you forgot to also add the now mandatory curly-braces... This is far-too-common source of bugs in noob-code. Almost all professionals, nearly allways allways use curly braces, most of the time ;-)
4. Variable names should be meaningful, except (IMHO) for loop counters... Ergo: I'd rename index plain old i, and minIndex to plain old j
    for ( int i=0; i<list.size()-1; ++i) {
      int wee = i; // wee is the index of the smallest-known-item in list.
      for ( int j=i+1; j<list.size(); ++j ) {Cheers. Keith.
Edited by: corlettk on 28/11/2009 09:49 ~~ This here fraggin forum markup friggin sucks!

Similar Messages

  • Need to sort two vectors at the same time! please help!

    I have
    vectorA: 2 4 9 1 7 6 8
    vectorB: two four nine one seven six eight
    i want to sort these two vectors in parallel
    what is the best way?
    i could just do Collection.sort(vectorA) and get
    1 2 4 6 7 8 9
    but i want the vectorB to have a corresponding order
    please help!!
    thanks

    public class Pair implements Comparable {
    private int value;
    private String name;
    public int getValue() {
    return this.value;
    public void setValue(int value) {
    this.value = value;
    public String getName() {
    return this.name;
    public void setName(String name) {
    this.name = name;
    public int compareTo(Object o) {
    Pair that = (Pair) o;
    return this.value - that.value;
    place both in a Collection (vector is a bad choice if you are going to do sorting LinkedList is better) the Collections.sort method will sort
    according to the compareTo method.

  • Sorting HashSet without using the tree set?

    Hi,
    I need to sort the hash set by using the comparator, if i use the comparator in tree set to sort my hash set then it will check the uniqueness condition also using the same comparator. So i will lose some elements in the set.
    So i want to sort no need to check the uniqueness.
    Is there any API is available in java to achieve this. Like sorting the list we use the Collections.sort method. Like this any API is available to sort the hash set or any other ways can we achieve this (without using tree set sorting the hash set.)?
    Thanks in advance.

    906738 wrote:
    Thanks for your reply.
    I had done those things earlier like you said, the application i am using is frequently running out of memory i don't want to use more objects. If i am converting to list then it will create the another object to hold the elements of the hash set. Because of this only i am seeking for any other API is available.Perhaps you should try to find the source of your memory problems in stead of doing your very best to not have to do that; the way you're trying to "solve" things now is only going to lead to epic failure, I mean you're now as far gone as trying to not create objects in an object oriented language.
    Try a profiler.

  • When I use the selection tool to move vector points and bend edges, I only see the change in wire frame.

    When I use the selection tool to move vector points and bend edges, I only see the change in wire frame.  Once I commit by letting go of the mouse button, the object does change.  It just previews with a wire frame. I would like to see the preview change on the solid object.  Is there a setting somewhere?
    I sure hope I am explaining this for people to understand .
    Thanks
    Ed

    Hi Ed,
    What do you mean by wire frame??And are you using selection or sub-selection tool since you have mentioned about vector point I doubt if it is sub-selection tool.Could you please attach a video demonstrating the issue where we see the mismatch in the preview and the output, so that we can understand the problem better and try to resolve it.
    Thanks,
    Sangeeta

  • In version 5, how do I use the selection tool to move objects?

    I can use the selection tool to select objects, but when I try to drag it, nothing happens. My workaround is to use the selection tool to select an object, and then use the transform tool to drag the object into its new position. Any help is greatly appreciated.

    is your object locked?
    Message was edited by: lilia@
    ... or perhaps your clicking on the content grabber?

  • I sent iTunes to trash. I was able to recover the program but have to "put back" songs one at a time. Is there any way to put back from trash using the "select all" command?

    I sent iTues to trash by mistake (trying to delete files from "yesterday"). I got the program back but have to "put back" songs one at a time. Is there a way to put back multiple songs using the "select all" command or anything else? Thanks for the help.

    The prgram is in one location and the library (media + library files) are in another. Sending it all to the trash would take some pretty delibrate multiple actions and digging through multiple folders, so I don't know how this was managed unless there's something in Snow Leopard that's new. Occasionally I have moved a file to the trash in Finder that I didn't want to and I can use Finder's "undo" to undo the last move. With many files...?

  • How to use the selection profile and status profile for production order?

    Hi expert,
       I want to know how to use the selection profile and status profile for production order. what's the usage for these two selection profile and status profile ?
      Please help me.
      thanks in advance.
      george.shi

    Hi George,
    There are are two types of statuses.One is system status and second one is user status.These statuses will tell us current situation of an order.
    We can't change system statuses.But we can create our own statuses through status profile.With this profile we can control user statuses.
    In this status profile,
    1.We define the sequence in which user statuses can be activated,
    2.We define initial statuses
    3. Allow or prohibit certain business transactions.
    Selection profiles are used to select the objects (say production orders) with different status combinations.We assign status profiles to selection profiles in BS42 T-Code.
    Regards,
    Raja.
    Edited by: Rajarao on Oct 30, 2008 6:21 AM
    Edited by: Rajarao on Oct 30, 2008 6:22 AM

  • To use the selection screen entry in another program

    dear all,
    i have a requirement that i want to use the selection screen entry of my zmodule pool to the selection screen of a zreport and want to use its output in my module pool.
    how could i do this in my module pool programing??
    i hope u get my question, i want to use the output of my zreport in my module pool with the same selection screen as given in module pool.,directly in my module pool output without opening my zreport seperately for this same selection screen data

    Hi,
      You can use SUBMIT statement in your module program to call the zreport program in background.
    Press F1 on Submit statement and you will find required detials of this statement. For using submit statement
    you have to create an internal table of type RSPARAMS and pass it in the submit statement.
    eg.
    DATA :
    *  table to be passed to background report 'ZREPORT1'
        int_rspar TYPE TABLE OF rsparams,
        ws_rspar TYPE rsparams.
    CONSTANTS: c_include     TYPE rsparams-sign               VALUE 'I',
               c_kind        TYPE rsparams-kind               VALUE 'S',
               c_between     TYPE rsparams-option             VALUE 'BT'.
    *Preparing the table to be passed to the background report.
    *populating SELECT-OPTION for knb1-kunnr (Customer Number)
    CLEAR : ws_rspar.
    ws_rspar-selname = 'S_KUNNR'. "Should be the name of select option as in                               the called report
    ws_rspar-kind = c_kind.
    ws_rspar-sign = c_include.
    ws_rspar-option = c_between.
    ws_rspar-low = '1'.
    ws_rspar-high = '100'.
    APPEND ws_rspar TO int_rspar.
    *populating SELECT-OPTION for knb1-bukrs (Company code)
    CLEAR : ws_rspar.
    ws_rspar-selname = 'S_BUKRS'.
    ws_rspar-kind = c_kind.
    ws_rspar-sign = c_include.
    ws_rspar-option = c_between.
    ws_rspar-low = 'a'.
    ws_rspar-high = 'z'.
    APPEND ws_rspar TO int_rspar.
    submit zreport
      with selection-table int_rspar
          EXPORTING LIST TO MEMORY
              and return.
    The above code will execute the zreport in backgournd.
    Now to get the output of the zreport :-
    *This internal table stores the value
    *Of output listed to memory
    DATA BEGIN OF itab_list OCCURS 0.
    INCLUDE STRUCTURE abaplist.
    DATA END OF itab_list
    * To read from the memory. The output of the program that is executed in background is then populated in the itab_list table.
    CALL FUNCTION 'LIST_FROM_MEMORY'
    TABLES
    listobject = itab_list
    EXCEPTIONS
    not_found = 4
    OTHERS = 8.
    * To write it onto the output
    CALL FUNCTION 'WRITE_LIST'
    EXPORTING
    WRITE_ONLY = 'X'
    TABLES
    listobject = itab_list
    EXCEPTIONS
    EMPTY_LIST = 1
    OTHERS = 2
    IF sy-subrc 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    Regards,
    Bhavesh.

  • I found my old ipod and i forgot the passcode. It doesnt have an home button so i dont know how to put it in recovery mode so i can restore it. Ive been using the assisted touch method. But what should i do to put it in recovery mode

    i found my old ipod and i forgot the passcode. It doesnt have an home button so i dont know how to put it in recovery mode so i can restore it. Ive been using the assisted touch method. But what should i do to put it in recovery mode so i can restore it.

    Use this program to place the iPod in recovery mode
    RecBoot: Easy Way to Put iPhone into Recovery Mode

  • HT4641 Im trying to print off my cv, page 1 prints off fine but page 2 does not, I'm using the selected template for curriculum vitae why does my page 2 not print?

    Im trying to print off my cv, page 1 prints off fine but page 2 does not, I'm using the selected template for curriculum vitae why does my page 2 not print?

    Hi @kots 
    I suspect your question would be better answered in the HP Enterprise Business Community, as your HP Printer is a commercial model.
    My technical expertise is with consumer products and software, I am sure the commercial folks would be happy to help if you re-post your question for them to answer. The HP Enterprise Business Community is an HP Forum designed for the Commercial and Enterprise customers to help one another. I am sure you will find some HP folks there to help too.
    Click here to view the Printing and Digital Imaging. When the page opens you will see the option to 'Log in' or 'Register Now' on the right. The commercial forums are separate from the consumer boards, thus you will need to register if you don't already have a commercial account.
    You may find the HP LaserJet M2727 Multifunction Printer series page helpful while you wait for somebody in the commercial Forum to respond to your inquiry.
    Best of luck.
    Please click the Thumbs up icon below to thank me for responding.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Please click “Accept as Solution” if you feel my post solved your issue, it will help others find the solution.
    Sunshyn2005 - I work on behalf of HP

  • Menu Creation and Using the SELECT soft key

    Hi,
    I am trying to design a menu similar to the thumbnail menus available in most phone these days.what i want is a set of icons placed in a tabular format ie rows and colums. the joystick control can be used to navigate thru the icons and using the select soft key ie the middle button of the soft keys, the next set of forms can be displayed.
    so far, i have created a form, used a few image item and used the Item's layout directive to arrange the imageItem as i want on the display. I can get the joystick to navigate between the imageItems however the select button doesnt fire any event.
    I have added a command to each of the items and set an ItemCommandListener.
    That approach seems to be working fine but it defeats my purpose. the reason being i had problems with the mapping of the command keys. For each display i had an option of going to the main menu and to the next screen. On the emulator it maps perfectly with the left key having the main menu and the right key having the "next form" button. But while implementing on the phone, the left key has the main menu but the right key shows "more options", when u click more options you get the "next form" button. This is happening in every form on display and makes it more tideous to use.
    Thats why i was hoping to get the select button working if possible. Any help would be much appreciated.

    Try searching J2mepolish.org plenty of work is done
    with Regards
    Rizwan

  • I would like to download a production desciption into my website like I have before, but it says I can't use the copy/paster method anymore. Why?

    I have a website - www.pawsitivepamperings.com, and I have been adding products for the last 6 months. I have been using the copy/paste method from my drop shipper. Since the end of last week, it hasn't been working. It has totally stopped my progress! I need help in using this function again - as soon as possible. Can you help me?

    I right click, and Copy from an HTML description from my drop shipper. Then I go to my website and right click to Paste.
    One of two things happens. (1) if it does copy, the text prints over the image; OR (2) I get a message that Firefox does not apply a Cut/Copy/Paste.
    The wording at the bottom of the description box says: Path: table> tbody> tr> td> p> font.
    I was told by my webmaster to eliminate the following but I don't see it on my products page: <table align="center" border="0" cellpadding="1" cellspacing="1" width="100%>.
    When I have been on a 'live chat' with my support team, a couple of them have overridden the issue and I could precede, but I go to the next product to add, the whole process starts again and I cannot proceed.
    Does this make sense?

  • Select a small area and then use the selected area to paint other areas of the image

    Hello
    My problem is a little hard to explain but I try.
    What I want is to select a small area and then use the selected area to paint other areas of the image. Do not know how to do it and if it's stamp tools or pen tools to be used?

    Howdy.
    Sounds like you're looking for the Clone Stamp Tool. Set to Aligned, the sampling point resets when you release the mouse after painting. Untic Aligned and the sampling point stays in the original spot for the next stroke. It's a good idea to clone onto a separate layer with Sample All Layers selected. Then you don't lose original pixels. Allows you a do over later.
    FWIW.
    Peace,
    Lee

  • Using the Process.getOutputStream() method

    Hi all,
    i have written a java program that executes System commands and returns output...
    this program works fine if you want to only execute the command and returns output...
    but suppose that the program that you executed waits for you to input something before returning ouput?!!
    i suppose i have to use the Process.getOutputStraem() method in my prog!
    but i don't know how to do that :-(
    can any one help me to refine the prog to handle this case !
    thanks a lot
    here is the code:
    import java.util.*;
    import java.io.*;
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        OutputStream os;
        StreamGobbler(InputStream is, String type)
            this(is, type, null);
        StreamGobbler(InputStream is, String type, OutputStream redirect)
            this.is = is;
            this.type = type;
            this.os = redirect;
        public void run()
            try
                PrintWriter pw = null;
                if (os != null)
                    pw = new PrintWriter(os);
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null)
                    if (pw != null)
                        pw.println(line);
                    System.out.println(type + ">" + line);   
                if (pw != null)
                    pw.flush();
            } catch (IOException ioe)
                ioe.printStackTrace(); 
    public class GoodWinRedirect
        public static void main(String args[])
            if (args.length < 1)
                System.out.println("USAGE java GoodWinRedirect <outputfile>");
                System.exit(1);
            try
                FileOutputStream fos = new FileOutputStream(args[0]);
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("java jecho 'Hello World'");
                // any error message?
                StreamGobbler errorGobbler = new
                    StreamGobbler(proc.getErrorStream(), "ERROR");           
                // any output?
                StreamGobbler outputGobbler = new
                    StreamGobbler(proc.getInputStream(), "OUTPUT", fos);
                // kick them off
                errorGobbler.start();
                outputGobbler.start();
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);
                fos.flush();
                fos.close();       
            } catch (Throwable t)
                t.printStackTrace();
    }

    it's true that i've copied it and pasted it...
    but i do understand how it works (really)
    the article mentioned at last that we could send input
    to the Program by invoking getoutputStream
    i guess that we should write a construtor for the
    streamGobbler class but this time using a
    OutputStreamReader and may be doing sth elseThe "Gobbler" is there to eat up whatever bytes become available on an InputStream (from the program's output). I don't think ou just want to try to use the same class to handle the program's input.
    The Gobbler can be used for eating up whatever comes out of any program--it' general, and doesn't rely on any particular output from the program (input to the Gobler). This is not the case for whatever writes to the program's input. You'll need to write what the program expects in the proper order.

  • Need clarification using the selection tool

    Hi all,
    I have some strange (to me) occurrences while using the 'selection tool'...
    Explanation:
    I'm using PSE11 on a Win 7 (64) PC.
    What I want to do is to create a new pic from an existing pic.  The existing pic's background is unsuitable for what I want.  But the FG is what I need.  I thought that selecting the FG object and placing it into a new pic would be what I needed using the <quick selection tool>.
    To do this, I am trying to use the <quick selection tool>.  I've had varying degrees of success using it.  One main thing I don't understand & pretty much renders my task useless, is the fact that whenever I use <refine edge> so that I can refine my edge selection, my pic is immediately lost or taken away.  Since I have no idea as to what's happening, I am forced to close the pic (W/O saving changes, of course) & then re-opening the pic.  All's well until I use the <refine edge> button again, then, my pic disappears AGAIN!
    There are a few more details about this <selection tool> that I'm muddy on.  Is there something where I can read more about its use?  I would love to know more, but how?  Where?
    I am not a constant user of PSE, rather,  I only use it on occasions.  Normally, I use its scanning features.  I may play around with a few other features, but I also know that PSE offers many other powerful features, I rarely, if ever, use.

    There are many selection tool and way to extract a subject.  There are more way in Photoshop then in Photoshop Elements you should ask over in the Elements forum to get answers suitable for elements users.  You may get answers here that are not possible to use in Elements. Photoshop Elements

Maybe you are looking for

  • Need Calendar Year as a Variable in the Caption of an Analysis Item WAD 7

    I am using Web Application Designer 7.X for the first time. I am modifying a template that has the following Analysis Item in it:            <bi:ANALYSIS_ITEM name="TABLE_4" designheight="300" designwidth="966" >                 <bi:WIDTH value="966"

  • How Do I Solve this Problem when Copying Library from Backup Disks?

    I recently had a pc problem that resulted in the repair company having to back up my hard drive (which included my I Tunes Library) onto DVDs. When trying to upload the ITunes library from the DVD to my new computer (after downloading I Tunes softwar

  • Safari bookmarks problem

    I use Safari 5.1.1. From one day to the next, my bookmarks disappear. Or if rearrange them, they pop back to the old arrangement. What gives? Anyone else having this issue? Any idea how to fix it? Thanks!

  • Can't open dynamic PDF-Filesin 8.2

    "\Schema\ApplicationData.xsd" not found. I can open it in Acrobat.

  • How to get Oracle Form Parameter Value into Oracle Report

    Hi, Please guide for the following: On a form, there is one Control Block (CB1), having two TEXT ITEMS, namely From_Date & To_Date respectively. The user inputs from and to dates, for example From_Date: 01-JAN-2009 and To_Date: 31-DEC-2009 and then p