Sorting an array using recursion

Hi! I am having some problems figuring out what is wrong with my code here. I need to sort an array of n given elements using recursion. What am i doing wrong here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
using namespace std;
int i=0, j=1, v[100], n;
void sort()
{
    int aux;
    if(j!=n){
        if(v[i]>v[j])
        {
            aux=v[i];
            v[i]=v[j];
            v[j]=aux;
        }
        i++;
        j++;
    }
    sort();
}
void citire()
{
    for(int q=1;q<=n;q++)
        cin>>v[q];
}
void afisare()
{
    for(int q=1;q<=n;q++)
        cout<<v[q]<<" ";
}
int main()
{
    cin>>n;
    citire();
    cout<<endl;
    afisare();
    cout<<endl<<endl;
    sort();
    afisare();
    return 0;
}
You have infinite recursion. The sort() function will keep calling itself until you stop the program.

1
2
3
4
void sort()
{
    sort(); // sort, sort, sort, sort, sort, sort...
}


Every time you write a recursive function, you must include a stop condition before calling recursively.

1
2
3
4
5
void sort()
{
    if (/* can call again */)
        sort();
}


Were you told to implement a sorting algorithm and use recursion?

See this page for explanations for various algorithms. (See Quicksort which uses recursive calls.)
http://www.cplusplus.com/faq/sequences/sequencing/sort-algorithms/
Thanks!
Topic archived. No new replies allowed.