Results 1 to 3 of 3
  1. #1
    artur is offline Member
    Join Date
    Nov 2011
    Posts
    15
    Rep Power
    0

    Default Recursive method to sort array

    Hi. I have to write a method to sort an array of objects alphabetically. The method has to :
    1) Determine largest item in the list.
    2) Swap largest item in the list with the last item in the list.
    3) Call method recursively to sort the sublist of size n-1.
    My code, finds the largest value and swaps it with the last value. But when I add recursive call the program gives me the stackoverflowerror null.

    Here is my code.
    Java Code:
    public static void selectionSortRecursive(Comparable[] list, int n){
           
         if(n <= 1){} 
          else
          {
                Comparable temp;
                Comparable largest = list[0];
                int index=0;
                 
                 for(int i = 0; i < n; i++){
                   if(largest.compareTo(list[i]) < 0){
                       largest = list[i];        
                       index = i;
                }
                  
                     
             }
                      temp = list[n-1];
                      list[n-1] = list[index];
                      list[index] = temp;
         }
          
           
           
                selectionSortRecursive(list,n-1);
        }
    Thank you for comments.

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default Re: Recursive method to sort array

    Try debugging the code by adding some println statements to see why it doesn't stop recursive calling.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default Re: Recursive method to sort array

    Your indentation stinks; fix it and you'll find your mistake.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. merge sort with recursive method (need help badlly!!)
    By zetalore in forum Advanced Java
    Replies: 0
    Last Post: 01-08-2011, 08:10 PM
  2. Array out of bound- Recursive Method
    By hpayandah in forum New To Java
    Replies: 2
    Last Post: 11-12-2010, 09:02 PM
  3. Recursive method using int array, help needed
    By chupalo17 in forum New To Java
    Replies: 4
    Last Post: 09-08-2009, 12:15 AM
  4. Replies: 1
    Last Post: 02-16-2008, 10:10 PM
  5. Replies: 2
    Last Post: 02-16-2008, 09:52 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •