Selection Sort Method help

The method below will not compile. The error reads" void is an invalid type for the variable selectionSort". What should I do? Also how would I invoke the method?
public static void selectionSort(double[] score, String[] name)
         for (int i=scores.length-1; i>=1; i--)
           double currentMax=scores[0];
           int currentMaxIndex=0;
           for (int j=1; j<=i; j++)
             if (currentMax<scores[j])
               currentMax=scores[j];
               currentMaxIndex=j;
           if (currentMaxIndex!=i)
              scores[currentMaxIndex]=scores;
     scores[i]=currentMax;
     String temp=names[currentMaxIndex];
     names[currentMaxIndex]=names[i];
     names[i]=temp;
     }Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

meepton wrote:
show me how.Why? you didn't write it, you don't understand it so I don't see any beneficial reason to help you. I suggest reading some tutorials about creating and using methods.
Mel

Similar Messages

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

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

  • Doubt in working of Arrays.sort method. help needed !!!!

    Hello Friends,
    I am not able to understand output of Arrays.sort method. Here is the detail of problem
    I wrote one program :
    public static void main(String[] args) throws ClassNotFoundException
         Object[] a = new Object[10];
         a[0] = new String("1");
         a[1] = new String("2");
         a[2] = new String("4");
         a[3] = new String("3");
         a[4] = new String("5");
         a[5] = new String("20");
         a[6] = new String("6");
         a[7] = new String("9");
         a[8] = new String("7");
         a[9] = new String("8");
    /* Sort entire array.*/
         Arrays.sort(a);
         for (int i = 0; i < a.length; i++)
         System.out.println(a);
    and output is :
    1
    2
    20
    3
    4
    5
    6
    7
    8
    9
    Question : Does this output is correct? If yes then on which basis api sort an array? I assume output should be 1 2 3 4 5 6 7 8 9 20.
    Can here any one please explain this?
    Thanks in advance.
    Regards,
    Rajesh Rathod

    jverd wrote:
    "20" and "3" are not numbers. They are strings, and "20" < "3" is exactly the same as "BA" < "C"The above is
    ... quote 20 quote less than quote 3 quote...
    but shows up as
    ... quote 20 quote less than quote...
    Weird.

  • 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

  • Selection Sort using Linked Lists

    As the subject says, I'm trying to implement a selection sort method on a linked list structure. I've already created a bubble sort, but I can't seem to get this method to work correctly. The Node and LinkedList classes were written by me, and I know they work correctly (because of the other methods work right).
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                boolean exchangeMade;
                while (pointer.getNext().getNext() != null) {
                    current = pointer;
                    exchangeMade = false;
                    iterationsOUTER++;
                    while (current.getNext() != null && !exchangeMade) {
                        if(current.getNext().getData() < pointer.getData()) {
                            int temp = pointer.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            exchangeMade = true;
                            iterationsINNER++;
                            swaps++;
                            comparisons++;
                        current = current.getNext();
                    pointer = pointer.getNext();
              //  System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }For instance, if I run this bit of code...
    LinkedList list = new LinkedList();
            list.insert(5);
            list.insert(29);
            list.insert(2);
            list.insert(1);
            list.insert(13);
            list.insert(8);
            list.insert(30);
            list.insert(3);
            sort.selectionSort(list);
            list.print();The output is...
    1
    8
    13
    3
    2
    29
    30
    5
    Anyone have any idea what is going wrong, or is anymore information needed?
    PS: I also need to create a insertion sort method with this, and I've been told I need to reverse the list for the insertion sort to work correctly. Any tips on how to implement this method too? :)

    I've changed it up a bit, and it works, but is this still a bubble sort? I've tried uncommenting that section that keeps track of the iterations and such, but I know they can't be right. Does this look correct? I basically just removed that boolean check...
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                while (pointer.getNext() != null) {
                    current = pointer;
                    iterationsOUTER++;
                    while (current.getNext() != null) {
                        comparisons++;
                        if(current.getNext().getData() < pointer.getData()) {
                            int temp = pointer.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            iterationsINNER++;
                            swaps++;
                        current = current.getNext();
                    pointer = pointer.getNext();
                System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }And no, I tried and I don't get a NullPointerException if I have a list of 2.
    Edited by: birdboy30 on Dec 3, 2007 7:23 PM

  • Selection Sort Algorithm

    I'm trying to implement a selection sort method with linked lists, but I just can't seem to get it to work correctly.
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                boolean exchangeMade;
                while (pointer.getNext() != null) {
                    current = pointer;
                    exchangeMade = false;
                    iterationsOUTER++;
                    while (current.getNext() != null && !exchangeMade) {
                        if(current.getNext().getData() < current.getData()) {
                            int temp = current.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            exchangeMade = true;
                            iterationsINNER++;
                            swaps++;
                            comparisons++;
                        current = current.getNext();
                    pointer = pointer.getNext();
              //  System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }If I test it with this code...
            LinkedList list = new LinkedList();
            list.insert(5);
            list.insert(29);
            list.insert(2);
            list.insert(1);
            list.insert(13);
            list.insert(8);
            list.insert(30);
            list.insert(3);
            sort.selectionSort(list);
            list.print();I get this as my output...
    8
    13
    1
    2
    29
    5
    30
    30

    Please clarify one thing for me:
    Is the Node class, something you made, or is it in the Java class library (there's quite a few named Node in there)? let me know....
    also, the LinkedList class has a generic type attached to it. Meaning you can store any data type in the LinkedList, but you have to specify what you want.
    example:
    LinkedList<String> strings = new LinkedList<String>();since the list is a parameter you don't have to initialize it, however you still need to specify what data type you're dealing with. I'd use "LinkedList<Object>" if you're not sure what type a user of this method may select, but it looks like you're gonna want to use "LinkedList<Node>".

  • 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

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

  • AAAGGGHH!!! Selection sort with external file!

    Hi, i am trying to sort marks from an external file in ascending order, using a selection sort via an existing class StudentMark.
    However, i am receiving 1 error when i compile it!!!!
    code below:
    import java.io.*;
    import java.util.*;
    class sort
         // method to display the contents of an array
         static StudentMark data[];
         static void displayData(int[] data)
              try
                   data = StudentMark.loadMarks();
                   for (int index=0; index != data.length; index++)
                        System.out.println(data[index]+"\t");
              catch(Exception e)
                   System.out.println(e.getMessage());
         static int positionOfLargest(int[] data, int limit)
         // method to return the position of the largest item
         // in the data with bounds 0..limit
              int largest = data[0];
              int indexOfLargest = 0;
              for (int index=1; index <= limit; index++)
                   if (data[index]> largest)
                        largest = data[index];
                        indexOfLargest = index;
              return indexOfLargest;
         public static void selectionSort(int[] data)
         // method to sort the contents of an data into ascending order
              int temporary;
              int position;
              int size=data.length;
              for (int index=size-1; index > 0; index--)
                   position=positionOfLargest(data, index);
                   // swap numbers
                   if (index != position)
                        temporary = data[index];
                        data[index] = data[position];
                        data[position] = temporary;
         public static void main(String[] args)
              int[] data;
              System.out.println("numbers before being sorted\n");
              displayData(data);
              selectionSort(data);
              System.out.println("numbers after being sorted\n");
              displayData(data);
    the error is: sort.java:14: incompatible types -                data = StudentMark.loadMarks();
    ^
    Can anyone see what i am doing wrong??
    Thanks!!

    static StudentMark data[];
    data = StudentMark.loadMarks();the error message "incompatible types" means that the type of data and the return type of StudenMark.loadMarks() are not compatible.
    in case of we don't know the return type of StudentMark.loadMarks() i could only guess:
    class StudentMark {
      public static StudentMark[] loadMarks() {
    }if you used that kind of method declaration you should change your declatation of the variable data:
    public static StudentMark[] data;then your codeline 14 shouldn't be a problem any longer.
    StudentMark[] data and StudentMark data[] ARE different!
    hope it helps.

  • Recursive selection sort stack overflow

    hi, first time posting here.
    i have to write a java method that implements a selection sort. This method must be recursive. ok not a problem. i have come up with this so far
        public int findMin(int index) {
            int min = index - 1;
            if (index < num.length - 1) min = findMin(index + 1);
            if (num[index] < num[min]) min = index;
            return min;
        public void selectionSort(int left) {
            if (left < num.length - 1) {
                swap(left, findMin(left));
                selectionSort(left + 1);
        public void swap(int index1, int index2) {
            int temp = num[index1];
            num[index1] = num[index2];
            num[index2] = temp;
        }which works fine until i toss in a lot of values into the array. this creates a stack overflow, and ive been told that i need to use the divide and conquer method of resolving this issue. I guess this means to split the array up and sort each half seperatly, again and agin, or so im told.
    My question is how do i go about doing this, i am at a loss. Any help at all would be great.
    thank you
    lance

    i get this when i push the array passed about 5500 in sizeI got no problem. Post a small demo code that is generally compilable, runnable and could reproduce your problem. See: http://homepage1.nifty.com/algafield/sscce.html and http://www.yoda.arachsys.com/java/newsgroups.html
    It is silly to implement selection sort with recursion, double-silly if you use double-recursion as your current code.
    /* silly but no OOME when used against 5500 element array */
    import java.util.*;
    public class RecursiveSelectionSort{
      static int[] num;
      public static int findMin(int index) {
        int min = index; // your code had a bug here
        if (index < num.length - 1){
          min = findMin(index + 1);
        if (num[index] < num[min]){
          min = index;
        return min;
      public static void selectionSort(int left) {
        if (left < num.length - 1) {
          swap(left, findMin(left));
          selectionSort(left + 1);
      public static void swap(int index1, int index2) {
        int temp = num[index1];
        num[index1] = num[index2];
        num[index2] = temp;
      public static void main(String[] args){
        Random rand = new Random();
        int n = 10;
        if (args.length > 0){
          n = Integer.parseInt(args[0]);
        num = new int[n];
        for (int i = 0; i < num.length; ++i){
          num[i] = rand.nextInt(10000);
        selectionSort(0);
        for (int in : num){
          System.out.print(in + " ");
        System.out.println();
    }

  • Sorting Methods for an Array

    I'm trying to sort an object array of bank accounts based on their balance. JGRASP doesn't like my calling statement, which I don't think is correct.
    My question is am I calling the method correctly (trying to set the bankArray[counter].getBalance()) and am I using the sort method correctly?
    my call method
    bankArray = bankArray[counter].selectionSort(bankArray[counter].getBalance(), counter);My sort method:
    public static void selectionSort (double [] sort, int length)
    for (int i = length; i < 1; i--)
    double currentMax;
    int currentMaxIndex;
    currentMax = sort[0];
    currentMaxIndex = 0;
    for (int j = 1; j < i; j++)
    if (currentMax < sort[j])
    currentMax = sort[j];
    currentMaxIndex = j;
    }//End if
    }//End for

    There are some points to notice:
    Point 1: Your method receive an array of double and an int, as you passing a double and an int.
    Point 2: Your algorithm doesn't work properly. First of all, the selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping it with the item in the next position to be filled. Also, note that you don't swap the array elements in any moment.
    Point 3: In Java, your selectionSort method don't need to receive a parameter to inform the array length. The array itself already have that information ("myArray.length").
    Point 4: About the call of your method, you made it as the selectionSort method returns an array of BankAccounts - Supposing that you represent a bank account through an BankAccount class and bankArray[i] is an array of [i]BankAccount objects. It's not true. As you can see, your selectionSort method returns void, or either, returns nothing.
    Observing those 4 first points, we can re-write your selectionSort method like this
         public static void selectionSort(double[] numbers) {
                for (int i = 0; i < numbers.length - 1; i++)
                  int minIndex = i;
                  for (int j = i + 1; j < numbers.length; j++)
                    if (numbers[j] < numbers[minIndex])
                      minIndex = j;
                  double temp = numbers;
              numbers[i] = numbers[minIndex];
              numbers[minIndex] = temp;
    Now, when I try to re-write the call, I noticed other important odd thing about your approach: The [i]selectionSort method was written to sort bankAccounts, but it receives an array of double values. Being thus, you must to previously create a double[] object filled with the accounts' balances and then sort it. But, once sorted, how can you return the balances to their proper account? There is no way to do it. You have to sort a bunch of BankAccount objects, instead of an array of balances...
    An intuitive implementation of this sorting cound be something like that:     public static void selectionSort(BankAccount[] accounts) {
              for (int i = 0; i < accounts.length - 1; i++) {
                   int minIndex = i;
                   for (int j = i + 1; j < accounts.length; j++) {
                        double
                             currBalance = accounts[j].getBalance(),
                             minBalance = accounts[minIndex].getBalance()                    
                        if (currBalance < minBalance)
                             minIndex = j;
                   BankAccount temp = accounts;
                   accounts[i] = accounts[minIndex];
                   accounts[minIndex] = temp;
    I noticed form your call that the [i]selectionSort method boleng to the BankAccount class. Once this method is static, It's strongly recomended that you invoke this method in a static way (from the class, instead of from an object).
    Here it goes a fictional BankAccount class and a TestBankAccount class. Read it, Run it, Study it, Understand it.
    package help.sun.imbrium;
    public class BankAccount {
         private double balance;
         private int number;
         public static void selectionSort(BankAccount[] accounts) {
              for (int i = 0; i < accounts.length - 1; i++) {
                   int minIndex = i;
                   for (int j = i + 1; j < accounts.length; j++) {
                        double
                             currBalance = accounts[j].getBalance(),
                             minBalance = accounts[minIndex].getBalance()                    
                        if (currBalance < minBalance)
                             minIndex = j;
                   BankAccount temp = accounts;
                   accounts[i] = accounts[minIndex];
                   accounts[minIndex] = temp;
         public BankAccount(int number, double balance) {
              this.balance = balance;
              this.number = number;
         public double getBalance() {
              return balance;
         public void setBalance(double balance) {
              this.balance = balance;
         public int getNumber() {
              return number;
         public void setNumber(int number) {
              this.number = number;
         public String toString(){
              return "[Account #" + number + " balance: $" + balance + "]";
    class TestBankAccount{
         public static void main(String[] args) {
              BankAccount[] accounts = {
                   new BankAccount(1, 154.23),
                   new BankAccount(2, 1554.23),
                   new BankAccount(3, 15.3),
                   new BankAccount(4, 854),
                   new BankAccount(5, -4.79),
              System.out.println("Unsorted:\n\t" + arrayToString(accounts, " "));
              BankAccount.selectionSort(accounts);
              System.out.println("Sorted:\n\t" + arrayToString(accounts, " "));
         private static String arrayToString(Object[] objs, String separator){
              StringBuilder sb = new StringBuilder();
              for (int i = 0; i < objs.length; i++) {
                   Object obj = objs[i];
                   sb.append(obj.toString());
                   if(i < objs.length - 1)
                        sb.append(separator);
              return sb.toString();

  • Doubt about select in method.

    Hi Gurus.
    In Webdynpro can we use Select in method?
    If dont , how we can use the select comand in method? And why is not permited.?
    Thanks

    Hi Ronaldo,
    Though system does not throw any errors if we write select queries in WD component controller/view controller but we should never write a DB queries like select, insert, update, etc because it has an impact on performance of web dynpro application.
    Web dynpro applications are heavy and it runs in front end and hence only the ui logic to be placed in WD components and the business logic/db queries to be placed in a model viz, class / function module, etc.Hence WD implementation should strictly follow the MVC architecture
    For more details on MVC in WDA, please refer the below links
    Web Dynpro Architecture (SAP Library - Web Dynpro for ABAP)
    Architecture of Webdynpro for ABAP - Web Dynpro ABAP - SCN Wiki
    Hence, you should use either a class / function module to place your business logic and call the methods/ function modules inside the WD component.
    In general, for every WD component, a assistance class will be attached and it assists the component with business logic. So, we can call the method of an assistance class in WD component.
    Hope this helps you.
    Regards,
    Rama

  • Why do I get "Select Input Method" dialog when trying to open tabs on some sites?

    This is what I'm experiencing with Firefox mobile on an Android tablet.
    On some sites, when I click a button which should open a new tab, I get the "Select Input Method" dialog box. First, I don't know why this dialog is popping up. Second, it is an empty dialog; there is nothing to select, only a heading that says "Select Input Method". When I touch the heading, I get another "Select Input Method" dialog, this time with "Android Keyboard" as the sole item to be selected. It is already selected. Touching it or backing up to dismiss it leaves me on the page I started on. Touching the original button which should open a new tab simply repeats the entire dialog sequence. Backing up from the original, empty dialog, does the same thing.
    Once or twice, by magic or something, I was able to get the page to open the new tab. But I cannot confirm what sequence of selecting or backing up out of the dialogs may have led to the correct behavior.
    Any help would be appreciated.

    kbrosnan,
    Thanks for the reply. Sorry it took so long to get back to you.
    My wife is working on a project so I'm a little light on details. Apparently she figured out that her Javascript is calling ShowModalDialog and this was what was causing the Select Input Method dialog to open. I don't fully understand the details but she's looking for a different way to do this. I believe she said she subsequently found out that the Firefiox mobile browser doesn't support ShowModalDialog.
    She's new to mobile web development (and I know nothing about it) so she's kind of feeling her way. If you have a good resource for how the FF Android mobile browser differs from the normal desktop browser, that wouldbe a big help, I think. Otherwise, thanks for you reply and she'll keep plugging away discovering what she needs to change in her program to make it work for mobile.
    Thanks.

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

Maybe you are looking for

  • Is the program from FiuneDeaalSuoft, and its associated links, causing problems?

    A program from FiuneDeaalSuoft somehow appeared in my Firefox Add-0ns as of 2 days ago (08212014) according to Control Panel-Programs. I don't recognize it, but possibly I mistakenly clicked on an acceptance interface without realizing it. The ad re-

  • Debit & credit not matching in GL view

    Hi Friends, I have 1 issue in case of my client. We are using ECC6.0. Document splitting is also active. My document in GL view is not balanced i.e.Total of Dr. items is not matching with total of Cr items. Kindly help. Thanks & Regards

  • WRT54GS NAT Settings Concerning Xbox 360 Setup

    My xbox 360 is connected to a Dell Inspiron B130 notebook via an Ethernet cable. The notebook is then connected wirelessly to a Linksys WRT54GS router. The router, finally, is connected to a Sprint DSL modem. My problem is that with this setup, whene

  • What is this called in Flash?

    I am interested in creating something like features section on this page http://www.nationalgeographic.com/ where you scroll through different images with a breif intro and link to go to the details page. I am trying to search for this but I am not s

  • Webservices Performance impact Vs. JCo

    Hi, We are about to begin development and we are evaluating about developing with Webservices in the Back End following this instructions /people/sridhar.k2/blog/2006/09/12/creating-and-exposing-bapi-as-web-service-and-using-it-in-web-dynpro or using