Recursive function to sort an array [closed]

我的未来我决定 提交于 2020-12-10 16:53:58

问题


I'm having trouble building a recursive function that sorts an integer array. At this point, I don't know any sorting algorithms, this is only my second CS course. I've seen a lot of solutions on here, but the issue with those solutions is that they have loops or nested conditions statements. In this function I cannot use loops or nested if statements, only single if/else statements.

I know you guys don't want to simply give answers since it takes away from the learning experience, but if I could just get pointed in the right direction I would greatly appreciate it.


回答1:


To write a recursive function-

  1. Write a function signature and assume that it will do your job with some magic.

  2. Now think about base condition i.e what will your function do in case of smallest valid input.

  3. Now write the induction step in which you call the same function on smaller input(generally).

    def sorting(arr):
    
        #Base Condition
        if len(arr) == 1:
            return
    
        #Induction
        last_num = arr[-1]
        arr.pop()
        sorting(arr)
        insert(arr, last_num)
    
        return arr
    
    def insert(arr, last_num):
    
        #Base Condition
        if len(arr) == 0 or arr[-1] <= last_num:
            arr.append(last_num)
            return
    
        #Induction
        val = arr[-1]
        arr.pop()
        insert(arr, last_num)
        arr.append(val)
    



回答2:


Check out Quicksort which is a recursive algorithm that will do exactly what you need. Let me know if you need help implementing it.




回答3:


Of Course there are merge sort and quick sort which use recursion and are among the best known sorting algorithms. Since you are a beginner it would be better if you start with relatively simpler ones. Here is the selection sort algorithm that uses recursion.

int selection_sort(int num[], int n) //n=array length
{
    int max = num[0];   
    for (int i = 0; i < n; i++) {
        if (num[i] > max) 
            max = num[i];
        num[i] = num[n - 1];
        num[n - 1] = max;       
    }

    if (n > 0) {
        selection_sort(num, n - 1);
    }
}



回答4:


I hope you have heard about divide and conquer algorithm, where we divide the given array with respect to a particular element, known as 'pivot' such that the lower partition of the array are less than the pivot and upper partition elements of the array are higher than the pivot. Quicksort is one of the best example of recursion.




回答5:


You can use one of simpliest algorithms, just add recursive call. E.g. this is algorithm close to InsertinSort. At each step, we look thorugh array up to hi, and swap current element with highest in case of current element is greater than highest one. At the end for each loop, hi posint to the start of arra, that is sortered:

public final class BubbleSort {

    public static void sort(int[] arr) {
        sort(arr, arr.length);
    }

    private static void sort(int[] arr, int n) {
        if (n > 1) {
            for (int i = 0; i < n; i++)
                if (arr[i] > arr[n - 1])
                    swap(arr, i, n - 1);

            sort(arr, n - 1);
        }
    }

    private static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    private SelectionSort() {
    }

}



回答6:


Simple answer in c++ Program

#include<bits/stdc++.h>
using namespace std;

void insert(std::vector<int> &v,int num)
{
    if(v.size()==0 || v[v.size()-1]<=num)
    {
        v.push_back(num);
        return ;
    }
    int num2=v.back();
    v.pop_back();
    insert(v,num);
    v.push_back(num2);

}


void  sortv(vector<int> &v)
{
    if(v.size()==1)
    {
        return;
    }

    int num=v.back();
    v.pop_back();
    sortv(v);
    insert(v,num);

}

int main()
{
    std::vector<int> v={1,4,3,5,6,7,1,2,3};
    sortv(v);
    for (auto i : v) {
       cout<<i<<" ";
    }
}


来源:https://stackoverflow.com/questions/32804626/recursive-function-to-sort-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!