Comparable interface selection sort

Hi,
I've created a Person Class with a comparable interface. And i've created an ArrayList People with varaibles from the person class in - First_name, Surname, Month(Birthday), Day(Birthday).
Now i need to use selection sort to sort my arraylist into birthday order. In the Person Class i have a method which gives each person a different number for every possible birthday there is.
I have created a selction sort but dont know how to call the birthday from my array list and then to sort it.
This is my code for the selection sort so far:
import java.util.ArrayList.*;
public class Main
public static void selectionSort(Comparable[] people)
for (int k = people.length-1; k>0; k --)
Comparable tmp;
int Large = 0;
for (int j=1; j<= k; j++)
if (people[j].compareTo(people[k]) <0)
Large = j;
tmp = people[Large];
people[Large] = people[k];
people[k] = tmp;
this method compiles but i need to sort the birthday and dont know how. Also i need to output the whole array in birthday order.
Any help would be very greatful.
Thanks
Dave

Hi,
If my understanding is right..
You are trying to sort with birthday as the primary sort criterria.
For doing that, you have to write the comparison logic inside the compareTo() method implemented in the Person class (Inherited from Comparable Interface).
i.e. The compareTo() method should use the the primary_sort_variable(here it is birthday or something derived from it) to return a boolean value for your need.

Similar Messages

  • Sort column by without case sensitive  using Comparator interface

    Hello,
    When i sorted my values of a column in a table it was showing all sorted upper case letters at top rows and all sorted lower case letters on bottom. So i would like to sort values without case sensitive order. Like. A, a, B, b, C, c....
    I am using Collection class to sort vector that contains the values of a column as an object and using Comparator interface to sort the values of a column in either ascending and descending order. It facilitates to compare two objects like.
    <class> Collections.sort(<Vector contains values of column to be sort>, <Comparator interface>);
    and in interface it compares two objects ((Comparable) object).compareTo(object);
    Now Let's suppose i have three values say Z, A, a to sort then this interface sorted in ascending order like A, Z, a
    but the accepted was A, a, Z. So how can i get this sequence. I would like to sort the values of a column without case sensitive manner.
    Thanks
    Ashish Pancholi
    Edited by: A.Pancholi on Dec 29, 2008 1:36 PM

    [http://java.sun.com/javase/6/docs/api/java/lang/String.html#CASE_INSENSITIVE_ORDER]

  • 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!

  • Comparable and comparator interface in java

    Hi All,
    How comparable and comparator interface works in java and when to use comparable and when to use comparator.please give me some example(code) as I am not able to understand the difference.
    Thanks
    Sumit
    Edited by: sumit7nov on May 17, 2009 4:45 AM

    Thanks,one more doubt.
    We have Collections.sort() method and we can sort any list by this method without implementing comparable or comparator interface.Then my question is when we need to implement comparable or comparator interface or when do we write our own compareTo() or compare() methods.
    Thanks
    Sumit

  • Using the Comparator Interface.Please Help.

    Hello there,
    I am trying out this example regarding the Comparator Interface.
    It works fine, but I havent really understood this at all.
    It deals with reverse sorting.
    import java.util.*;
    class MyComp implements Comparator {
    public int compareTo(Object a,Object b)
    String aStr,bStr;
    aStr = (String)a;
    bStr = (String)b;
    return bStr.compareTo(aStr)
    class MyComparator {
    public static void main(String[] args) {
    // Create a Tree Set
    TreeSet ts = new TreeSet(new MyComp());
    ts.add("C");
    ts.add("A");
    ts.add("P");
    ts.add("Z");
    ts.add("B");
    System.out.println(ts)
    Output : [Z, P, C, B, A]
    I have not understood the following at all:
    1) We are implementing the Comparator Interface in class MyComp.
    Now where is this being called in the MyComparator class?
    2) How is the reverse sorting taking place.?
    How is this comparing the different instances of the MyComparator class
    when I havent even instantiated the MyComparator class ?
    3) How is the interface method compare To(Object a,Object b) being invoked?
    Please can some please answer my questions.
    Regards

    class MyComp implements Comparator {
    public int compareTo(Object a,Object b)
    String aStr,bStr;
    aStr = (String)a;
    bStr = (String)b;Your reverse ordering is happening here.
    If you were to write
    return aStr.compareTo(bStr)
    the ordering would be in normal order.
    >
    return bStr.compareTo(aStr)The comparator that the treeSet uses is declared and instantiated here
    TreeSet ts = new TreeSet(new MyComp());
    1) We are implementing the Comparator Interface in
    class MyComp.
    Now where is this being called in the MyComparator
    or class? The comparator is being used by the TreeSet to order your entries
    >
    >
    2) How is the reverse sorting taking place.?Explained above. For further explaination look up comparator and String.compareTo()
    How is this comparing the different instances of
    of the MyComparator class
    when I havent even instantiated the MyComparator
    or class ?Also explained above
    3) How is the interface method compare To(Object
    a,Object b) being invoked?Internally by the TreeSet
    I hope this helped a little

  • How to use the Comparable Interface?

    Now I have a question and I don't quite understand what the book explains. How does the comparable interface work? How can you redefine the equals implementation? How can you implement a compareTo? and how does this works with arrays? Thanks amigos......

    Not sure how to answer your question "how does the Comparable interface work" - what do you mean by "work"? It's purpose is to supply a known method that can be used to define an ordering on lists of objects. To do this you need to know how two objects compare to each other (less than, equal to, greater than) - and that's what the compareTo method gives you.
    You redefine the equals implementation by overriding the equals method - just declare a method in your class that has the same signature as equals and you're good.
    Your implementation of compareTo depends on your class. You just need to define how your classes compare to each other - for instance, assume you have an "Employee" class, that has an employee number and first name and last name fields. You want the natural ordering of lists of Employees to go in order by employee number. Define your compareTo method like:
    public int compareTo(Object o) {
        Employee emp = (Employee)o;
        if (emp.getEmployeeNumber() < this.getEmployeeNumber()) {
            return -1;
        else if (emp.getEmployeeNumber() == this.getEmployeeNumber()) {
            return 0;
        else {
            return 1;
    }You can sort arrays of things via the Arrays.sort method, which takes the array to sort and a Comparator (not Comparable) reference. The Comparator interface provides the same idea as the Comparable interface, but it's a stand-alone object that handles the comparison, as opposed to a method of some particular class. The compareTo method of the Comparator interface takes two Object references and returns how they compare.
    Good luck
    Lee

  • Selection Sort type iteration with LinkedList

    Hi,
    It seems like Java's ListIterator isn't especially great for doing a "compare every element to every other element" traversion (like the type used in selection sort).
    For example, this code works fine:
    for(ListIterator<T> i = list.listIterator(); i.hasNext();) {
         T a = i.next();
         for(ListIterator<T> j = list.listIterator(j.nextIndex()); j.hasNext();)
              compare(a, j.next());
    }But LinkedList.listIterator(int) is a really poor choice because the iterator has to start at one end and make its way towards the middle before it's returned. So it's not very fast.
    I would do this:
    for(ListIterator<T> i = list.listIterator(); i.nextIndex() < list.size()-1;) {
         T a = i.next();
         ListIterator<T> j = i.clone();
         for(j.next(); j.hasNext();)
              compare(a, j.next());
    }except that ListIterator.clone() isn't defined. There's also no copy constructor like in C++.
    Any ideas?

    Another reason not to use iterators. I don't know
    what those "structural modifications" are but they
    are likely to make the iterators fail via
    ConcurrentModificationException.
    Yeah, I figured that one out pretty quickly.
    And just another comment: you seem to be allowing
    your brain to be fogged by the idea of choosing the
    fastest method. The result of this is that you don't
    get any working methods at all. Don't optimize yet.That's valid. I actually have it working now, but based on the (minimal) experience I've had I always pick the most appropriate collection and then work it out from there.
    Something inside me dies whenever I see remove(0) called on a long ArrayList.

  • Help needed badly for selection sort

    I posted this on the other forum but haven't gotten a reply. I have a class that compares the zip codes of a file that is read into the code and store as objects. Now I have to sort the information by the zip codes this is what I have so far and I do not know what I am doing wrong with the selection sort. This is the first time I am doing selection sort.
    Here is my .txt
    10
    Dillin Jake York PA 17409
    Valdir John Chicago IL 98098
    Morphy Bob Harrisburg PA 73829
    Spears Johnathan Chicago IL 09182
    Simpson Bloo Los Angeles CA 94840
    Griffin Taylor York IL 49283
    Cartmen Eric Philadelphia PA 28192
    Connaly Teds Springfield IL 12930
    Marsh Stan Miami FL 48392
    William Thomas Reno NV 39029
    and this is the code:
    import java.util.*;
    import java.io.*;
    import java.util.Scanner.*;
    public class TestCustomer6 {
      public static void main (String[] args) throws FileNotFoundException {
        Scanner scan = new Scanner (new File ("customerData.txt"));
        int numLines = scan.nextInt();
           Customer2[] customer;
         customer = new Customer2[40];
        for (int i = 0; i < numLines; i++) {
          String fName = scan.next();
          String lName = scan.next();
          String city = scan.next();
          String state = scan.next();
          int zip= scan.nextInt();
         Customer2 newObj = new Customer2(fName,lName,city,state,zip);
        customer=newObj;
    public static void selectionSort(int[] array)
    {int count;
       for (count = 0; count < array.length; count++)
          int indexOfMin = findMinimum (array, count);
           swap (array, count, indexOfMin );
         public static int findMinimum (int[] array, int startIndex)
    {int mycount;
         int indexOfMin = startIndex;
           for(mycount = startIndex + 1; mycount < array.length; mycount++)
              if (array[mycount] < array[indexOfMin]
    indexOfMin = mycount;
    return indexOfMin;
         public static void swap (int[] array, int preIndex, int nexIndex)
    double temp = array[preIndex];
    array[nexIndex] = array[preIndex];
    array[nexIndex] = temp;
    the class:
    import javax.swing.*;
    class Customer2{
        public static final int FNAME = 0;
        public static final int ZIP = 1;
        private static final int LESS = -1;
        private static final int EQUAL = 0;
        private static final int MORE  = 1;
        private static int compareAttribute;
         private String firstName;
         private String lastName;
         private String city;
         private String state;
         private int zip;
        static {
           compareAttribute = FNAME;
         public Customer2(){
         firstName = " ";
         lastName = " ";
         city = " ";
         state = " ";
         zip = 0;
         public Customer2(String f, String l, String c, String s, int z){
              this.firstName = f;
              this.lastName = l;
              this.city = c;
              this.state = s;
              this.zip = z;
              System.out.println(this.toString());
        public static void setCompareAttribute( int attribute ) {
            compareAttribute = attribute;
        public int compareTo( Customer customer, int attribute ) {
            int comparisonResult;
            if ( attribute == ZIP ) {
                int p2zip = customer.getZip( );
                if (this.zip < p2zip) {
                    comparisonResult = LESS;
                } else if (this.zip == p2zip) {
                    comparisonResult = EQUAL;
                } else {
                    assert this.zip > p2zip;
                    comparisonResult = MORE;
            } else { //compare the name using the String class�s
                    //compareTo method
                String    p2fname = customer.getFirst( );
                comparisonResult = this.firstName.compareTo(p2fname);
            return comparisonResult;
        public int compareTo( Customer customer ) {
            return compareTo(customer, compareAttribute);
         public String getFirst(){
              return firstName;
         public String getLast(){
              return lastName;
         public String getCity(){
              return city;
         public String getState(){
              return state;
         public int getZip(){
              return zip;
         public String toString(){
              return  getFirst() + ",  " + getLast() + "     " + getCity() + "     "
              + getState() + "     " + getZip();

    1) Your code doesn't compile;
    2) You don't call your selection sort method anywhere;
    3) Your selection sort attempts to sort an int array which doesn't make sense;
    4) You don't use the comparison methods defined in your Customer2 class;
    5) I think that you've just copied/pasted several code fragments;
    6) Your indentation style is highly inconsistent (also see 5).
    kind regards,
    Jos

  • Comparable and Comparator Interface - Collections

    Hi All
    Please let me know when to use Comparable interface and Comparator interface. ?
    Any sort of information is highly appreciable .
    Matt

    Matt wrote:
    @ jverd      
    So, when you googled, and found tutorials, and worked through those tutorials, and read the javadocs for those classes, what in particular did you not understand?If everything would work like that what will be the use of forums like this , It does work like that, for people who aren't lazy. The use of these forums, as indicated by my first reply, is among other things, when you've done your own research, as you should do, and run into something you don't understand.
    so dont try to be smart :(Maybe you should try to be smarter.
    Lets try not to abuse the forum with exchanges like this. The only abuse so far has been you expecting the forum to be a substitute for doing your own research.
    I know how to use Comparable and Comparator but dont know when to use these in a real time application.That statement says nothing about your problem. The only information it carries is that you don't know what the term "real time" means.

  • Comparator for Generic Sorting

    Hi,
    I have a number of reports for which sorting is required on all columns. Each of these reports has a corresponding class, the columns correspond to the attributes of the class
    Arrays.sort(Object[] objArray,Comparator c) is used for the sorting.
    I have a generic class implementing Comparator interface.
    The compare(Object o1,Object o2 ) method of this class retrieves the values of the columns on which the comparison is to be made as:
    Object val1=Class.forName(o1.getClass().getName()).getMethod(methodName,null).invoke(o1,null);
    Object val2=Class.forName(o2.getClass().getName()).getMethod(methodName,null).invoke(o2,null);
    where methodName is the name of the accessor method for the column. val1 and val2 are then compared.
    The question is whether a generic comparator class can be implemented without using the reflection mechanism.
    Thanks ,
    Pratibha

    sure, use an interface and upcasting
    interface HasColumn {
      Object getColumn();
    Object val1 = ((HasColumn)o1).getColumn();
    Object val2 = ((HasColumn)o2).getColumn();Be sure that either all Objects in the Array implement HasColumn,
    or check instanceof HasColumn / catch the ClassCastException and do alternative comparing in the case of an "alien" Object.

  • Select Sorting in prompt level

    I have below requirement from user.
    Prompts:     Loan Id
              Loan Type
              Sort by Account Number/Sale Type
    Basically when user run the report, it should prompt below three fields.
    Loan Id
    Loan Type
    Sort order with a drop down list which has values Account Number/ Sale Type.
    i.e., user should be able to select sort order he wants for both Account Number/ Sale Type before running the report at
    prompt level.
    Does anyone know the best way to accomplish this?.
    Thanks,
    ven
    Edited by: Ven Men on Jan 21, 2009 8:32 PM

    Hi Deb,
    Thanks for your reply. I need little more clarification from you regarding Ascending/Descending and group by.
    Please see my comments below.
    1) Created a prompt at the universe level where users can choose their sorting option, ie. Ascending or Descending.
        How did you create this. What I did is I created a derived table in Universe with below code.
       "Select distinct table.Account_Number from table order by 1". It just does only Ascending.
       Then I created a prompt, called Sort_Order, in designer as 
       '1'!=@Prompt('Sort_Order','A',{'Account_Number'},mono,Not_Persistent))
      It is not parsed with a Parsing Result as Parse failed: Exception: DBD, ORA-00903: invalid table     name   State: N/A
    Since I am not taking this value from database table, I went ahead and created this prompt and exported universe.
      What I understood from your point is I need to create two different prompts, once for Ascending and one for Descending. Please
      let me know if I am going wrong.
    2) In the WebI report, create two variables, one for Ascending and Descending. The formulas would be something like:
       cv_Ascending: if(userresponse("Sort order prompt text here")="Ascending";MyField)
       cv_Descending: if(userresponse("Sort order prompt text here")="Descending";MyField)
       I created variable as Sort_Act_Num =if(UserResponse("Sort_Order") = "Account_Number"; [Account Number]; 0).  This just sorts in Ascending order only and when I want to change it to descending, it is not working.
    3) Put the cv_Ascending variable in column one set to sort ascending and put cv_Descending variable in column two set to sort descending. (The column with the value that isn't selected is always null so it's sorted on nothing)
    4) Since you can't really "hide" columns in WebI, you have to fake it. Set the font color to white (or whatever color your background is) and the width to zero (0) - unfortunately, it won't let you set it to 0, it will default to .02. Turn off the borders. The columns will in effect be "hidden" and disappear.
    I've done the same thing with grouping, by creating a variable and using it as a section break. Works like a charm.
    For grouping, do I need to create any prompts or variables in designer level? Also in report level, is the code same as above to create variable for grouping.
    Please let me know..
    Thanks,
    Ven Men

  • Select Sorting at prompt level

    Hi,
       How to select sorting parameter from prompt level?  I have followed the thread [Select Sorting in prompt level  |Re: Select Sorting in prompt level;. I got struck while creating " Prompt - Sort Order" object. How to do this?
    Regards,
    Malini.V

    Hi folks,
    I am a report designer and I use BOXI r2 sp4. After researching the boards, I asked my design team to create the Sort-Order prompt object at the universe level.
    From what I understood, they created it in an independent dervived table. I need to have it joined to another table that contains the "measures" but I don't know what kind of joins should be constructed.
    In the report, I'd like to use it for something like the following:
    >if(Prompt - Sort Order="Descending";cost of service)...
    I would greatly appreciate the advice of the SMEs on how to complete this requirement.
    Wannetta
    Edited by: Wannetta Thomas on May 18, 2009 7:49 PM

  • Selection Sorting of Data type (Char)

    public class CharSortTest {
        public static void main(String[] args) {
            char[] letters = {'j', 'a', 'z', 'y', 'x'};
            char min = 0;
            char swap = 0;
            for (int x = 0; x <= letters.length - 1; x++) {
                min = letters[x];
                for (int i = x + 1; i <= letters.length - 1; i++) {
                    if (letters[i] < min) {
                        min = letters;
    if (letters[x] != min) {
    swap = letters[x];
    letters[x] = min;
    min = swap;
    for (int p = 0; p <= letters.length - 1; p++) {
    System.out.println(letters[p]);
    }output:a
    a
    x
    x
    xi followed the logic of selection sorting.. i even checked the integer values of each character in my array
    but why is my program not sorting                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    vajj wrote:
    public class CharSortTest {
    i followed the logic of selection sorting..Obviously you didn't.
    Put in print statements at each step so you can see exactly what's happening--varaibles' values, code paths being followed, etc.

  • Selection Sort troubles

    I am doing a practice exercise involving a Selection Sort. I keep getting 2 errors when I compile and not sure what to do to fix them. Thanks in advance for your help! Here are the two errors:
    SortArray.java:79: illegal start of expression
         private void swapEm ( int indexCheck, int min ){
            ^
    SortArray.java:67: cannot resolve symbol
    symbol  : method swapEm  (int,int)
    location: class SortArray
               swapEm( indexCheck, min );
                     ^Here is my code:
    import java.lang.Math.*;
    public class SortArray {
         * Main method for program.
         * @param  args
        public static void main ( String args[] ){
         int array[] = new int [25]; //variable for array
          * For loop to populate the array with numbers ranging
          * from 0-100 inclusively and then
          * printing them out on the screen.
         for ( int index = 0; index < array.length; index ++ ){
             array[index] =( ( int ) ( Math.random() * 101 )  );
             System.out.println( array[index] );
          * For loop that iterates through array and sorts the array
          * in ascending order.
         int min;
         for ( int indexCheck = 0; indexCheck <  array.length -1;
               indexCheck ++ ){
             min = indexCheck;
             for ( int index = indexCheck + 1; index < array.length;
               index ++ ){
              if ( array[index] < min ){
                   min = array[index];
               swapEm( indexCheck, min );
          * Swaps the values of the array to put them in order.
          * @param one a value of type 'int'
          * @param two a value of type 'int'
         private void swapEm ( int indexCheck, int min ){
             int temp = array[indexCheck];
             array[indexCheck] = array[min];
             array[min] = temp;
         System.out.println();
         for ( int intCounter = 0; intCounter < array.length;
               intCounter ++ ){
             System.out.println( array[intCounter] );
    }//SortArray.java

    This is how i would do it:
    for ( int index = 0; index < array.length; index ++ ){
                   array[index] =( ( int ) ( Math.random() * 101 )  );
                   System.out.println( array[index] );
              System.out.println("-----------");
              /* To sort the array in ascending order
              for (int i=0; i<25; i++) {
                   for (int j=i+1; j<25; j++) {
                        if (array[i] > array [j]) {
                             int temp = array;
                             array[i] = array [j];
                             array[j] = temp;
              for (int i=0; i<25; i++)
                   System.out.println ("" + array[i]);
    All inside your main() method, without even using other methods.
    Calin

  • Swap Counter in simple Selection Sort method

        void sortSelection(List object)
             int swapCount=0;
               for(int i = list.length; i >= 2; i--)
                 int maxIndex = 0;
                        for(int j = 1; j < i; j++)
                             if(list[j] > list[maxIndex])
                                  maxIndex = j;
                   int temp = list[maxIndex];        //
                   list[maxIndex] = list[i-1];         //         Is the problem here?        
                   list[i-1] = temp;                     //
                   swapCount++;                     //
              System.out.println("\n" +swapCount+ " swaps were needed. ");
        }This is a pretty simple selection sort method. But I am fairly sure that I am incorrectly counting swaps with the code. I have defined a "swap" as when two array indices have their values switched. I am convinced that there is something wrong because the array of numbers is randomly generated, and yet the swapCount counter is always equal
    to (list.length-1) when it prints out. I would think it should be different every time. I indicated the line where I believe the problem lies, but I am not for sure. Thanks everybody.

    List of Random Integers, then sorted:
    9, 29, 30, 42, 53, 58, 59, 64, 66, 69, 74, 79, 79, 87, 95
    9 swaps were needed.then sort again (descending) and get this:
    95, 87, 79, 79, 74, 69, 66, 64, 59, 58, 53, 42, 30, 29, 9
    1 swaps were needed.I'm pretty sure that isn't correct. But forgive me if I did not specify that it was to work in descending order as well.
    So I tried this:
    void sortSelection(List object)
             int swapCount=0;
               for(int i = list.length; i >= 2; i--)
                 int maxIndex = 0;
                        for(int j = 1; j < i; j++)
                             if(list[j] > list[maxIndex])
                                  maxIndex = j;
                  if (maxIndex != (i-1) && ascending==true)
                       int temp = list[maxIndex];
                        list[maxIndex] = list[i-1];                             
                        list[i-1] = temp;   
                        swapCount++;
                  else if (maxIndex != (i+1) && descending==true)
                       int temp = list[maxIndex];
                        list[maxIndex] = list[i-1];                             
                        list[i-1] = temp;   
                        swapCount++;
    } adding the i+1 (because it is going in a different order)...and I think I solved it!

Maybe you are looking for

  • Inner classes in ABAP

    Hello! Is it possible to declare inner classes, that is, classes within classes in ABAP? If yes, please provide example. Thanks! Kind regards, Igor

  • Read pixel from text file

    Hi, is it possible to retrieve an image just by reading some parameters or its pixel from a text file? If yes, could anyone give me some ideas on how to do that? How do you also retrieve a specific line or value from a text file? Thanks.

  • Photoshop or InDesign

    I work for a non-profit and they need a program to design their own post cards, brochures, print ads and various other mail outs, especially for special events. They have a very limited budget and want to buy a single license for either Photoshop or

  • Magic Trackpad freezes after batteries changed

    The past few times my Magic Trackpad batteries have needed replacing, it loses its bluetooth connection and cannot be found.  The only way I can get things going again is to shut down my iMac with the power button and restart.  I believe this has onl

  • Walk in Process in SAP E Recruiting

    Hi Experts, In SAP ECC 6 E Recruiting if we publish a requisition to Campus channel then a URL is generated. Could some one explain this functionality. Also in case of URL does applicant need to register himself & how is this different from normal ap