1

I am working on trying to write a program where a user will enter 6 strings and then it will sort the array in reverse alphabetical order using a recursive method. This is one concept I do not understand despite multiple videos, readings and attempts. Any support and insight is greatly appreciated. Thank you.

import java.util.Arrays;
import java.util.Scanner;

public class SRecusion {


    public static void sort2 (String[] sort2) {
        int i;
        int min = 0;
        int max;

        for (i = 0; i <sort2.length -1; i++) {
            if (sort2[i].charAt(0)> sort2[i=1].charAt(0)) {
                sort2[i] = sort2[min];
            }
            else {
                min = (sort2(sort2[i-1]));
            }
        }
    }



    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String [] test = new String[6];
        Scanner scnr = new Scanner(System.in);
        String userEntry = "";

        for(int i = 0; i <= test.length - 1; i++) {
            System.out.println("Please enter a word:");
            test[i] = scnr.nextLine();
        }

        sort2(test);




            System.out.println("your list is" + Arrays.asList(test));
            System.out.println();

        }

}
5
  • You are currently not using a recursive sort, are you saying you want to change this current code to a recursive sort? What have you tried? Commented Oct 11, 2018 at 3:19
  • Yes I want it to be changed to a recursive sort. Commented Oct 11, 2018 at 3:27
  • is this a homework assignment where you are not allowed to use built in functions? also for a list of just six items using a recursive sort is like taking a sledge hammer to a nail. Too much power and will not really speed up your program Commented Oct 11, 2018 at 3:31
  • Yes it is for an assignment where we cannot use built in functions like sort. I agree it seems like a lot for a small sample size. I just have not been able to grasp the recursive concept. Commented Oct 11, 2018 at 3:36
  • Now I fully understand what you are asking and why. Thank you for letting me know answer incoming. Will take me some time to type/copy code and explanation Commented Oct 11, 2018 at 3:37

3 Answers 3

1

Sorting is a pretty broad topic as there are many different sorting methods (quicksort, merge sort, etc.) However, a pretty basic and simple sorting method is bubble sort. Although it isn't the fastest one, it's pretty easy to understand and code using recursion.

Essentially, bubble sort with iterate through the elements in pairs of 2 and swap the two elements if they're in the wrong order.

For example, let's sort (3, 2, 5, 4, 1) using bubble sort.

(2, 3, 5, 4, 1) First, it'll look at the first two elements swap them if needed. Since 3 is greater than 2, it'll swap them.

(2, 3, 5, 4, 1) Next, it'll look at 3 and 5. Since 3 is less than 5, there is no need to swap

(2, 3, 4, 5, 1) It now looks at 5 and 4 and swaps them.

(2, 3, 4, 1, 5) Finally, it looks at 5 and 1 and swaps them.

Now start from the beginning and repeat the whole process. The sorting ends if exactly 0 swaps are made during an iteration.

If you're still a bit confused, try watching a tutorial on bubble sort or visit this link.

Sign up to request clarification or add additional context in comments.

Comments

0

So from what I was asking above as to why you need a recursive sorting algorithm Here it goes I will try to explain how recursive sorting works. It took my some time to figure it out as I am sure it does for most people who first come in contact with it.

public static void Qsort(int[] array, int start, int end)
{
    //find the current center of the whole or parital array part I am working on.
    int center = (start+end)/2;
    ///System.out.println("\n This is the center : " + center);
    int pivot, i, pivotplace;
    i = 0;
    pivot = 0;
    pivotplace = 0;
    //if start = end then we are at a single element.  just return to the previous iterative call.
    if(start == end)
    {
       // System.out.println("\n Inside base case return :");
        return;
    }
    //find the pivot value we are using.  using a 3 prong selection we are assured to at least get some type of median value and avoid the N^2 worst case.
    pivot = getpivot(array[start], array[center], array[end]); //gets median value of start, center and end values in the array.
   // System.out.println("\n pivotvalue is  : " + pivot);
    //find where the current pivot is located and swap it with the last element in the current portion of the array.
    if(array[start] == pivot)
    {
        //System.out.print("\n Inside pivot at start");
        swap(array, start, end);
    }
    else
    {
        if(array[center] == pivot)
        {
            //System.out.print("\n Inside pivot at center");
            swap(array, center, end);
        }
    }
    //due to iteration the pivot place needs to start at the passed in value of 'start' and not 0.
    pivotplace = start;
    //due to iteration the loop needs to go from the passed in value of start and not 0 and needs to go 
    //until it reaches the end value passed in.
    for(i = start; i < end; i++)
    {
        //if the current slot of the array is less than then pivot swap it with the current pivotplace holder
        //since the pivotplace keeps getting iterated up be each swap the final place of pivot place
        //is where the pivot will actually be swapped back to after the loop cpompletes.
        if(array[i] < pivot)
        {
            //System.out.print("\n Swapping");
            swap(array, i, pivotplace);
            pivotplace++;
        }
    }
    //loop is finished, swap the pivot into the spot it belongs in.
    swap(array, pivotplace, end);
//there are 2 cases for recursive iteration.
//The first is from the start to the slot before the pivot
if(start < pivotplace){Qsort(array, start, pivotplace-1);}
//the second is from the slot after the pivot to the end.
if(pivotplace+1 < end){Qsort(array, pivotplace+1, end);}

}

public static int getpivot(int a, int b, int c)
{
    if((a > b)  && (a < c))
    {
        return a;
    }
    if((b > a)  && (b < c))
    {
        return b;
    }
    return c;
}
public static void swap(int[] array, int posa, int posb)
{
    int temp;
    temp = array[posa];
    array[posa] = array[posb];
    array[posb] = temp;
}

This is a basic Quick Sort or recursive sort I wrote this while in programming classes. You will probably not need to use the getpivot code as you are dealing with a small set of strings, but if you do some research you will see using a possible sample of 3 drastically speeds up the recursion due to balanced work load of the recursion tree.

3 Comments

Now all you have to do is pass in your array of strings decide the pivot and also how you want it sorted and change the code accordingly. as you know how to see if one string is less then or greater in alpha than another this should not be that hard.
I hope this helps in understanding as I put in a lot of explanation. if you have any questions please feel free to ask and I will do my best to answer them tomorrow morning,
Thank you so much I greatly appreciate the support and help. Like I said this is one concept I just cannot get my brain to grasp.
0

Sort Array using recursion in kotlin

    fun main() {
        print(sortArray(arrayListOf(1,3,2,6,8,3)))
    }
    
    fun sortArray(arr: MutableList<Int>): MutableList<Int>{
        if(arr.size==1) {
            return arr
        }
        val lastValue = arr.last()
        arr.removeLast()
        sortArray(arr)
        insert(arr, lastValue)
        return arr
    }
    
    fun insert (arr: MutableList<Int>, value: Int): MutableList<Int> {
        if(arr.size == 0 || arr.last() < value) {
            arr.add(value)
            return arr
        }
        val lastValue = arr.last()
        arr.removeLast()
        insert(arr, value)
        arr.add(lastValue)
        return arr
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.