Public Group

# Selection Sort

This topic is 4854 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

ok I needed to Write a Selection Sort Recursivley and Non Recursivley. that compiles but it doesnt do anything?

int* Sort(int a[], int l)
{

int length=l;
int i;
int largest=0;
int temp;
for(i=0;i<length;i++)
{		if(a>a[largest])
largest=i;

}
temp=a[largest];
a[largest]=a;
a=temp;
return (Sort(a, length-1));

}
void output(int t[],int length)
{
for(int i=0;i<length;i++)
cout<<t<<" ";
cout<<endl;
}

int main()
{
int A[]={5,2,8,3,10};
cout<<"Array sorted with recursive Selection Sort"<<endl;
output(Sort(A,5),5);
return 0;
}


##### Share on other sites
How sloppy of you.

Try to prove the algorithm terminates, it should tell you what is wrong.

##### Share on other sites
deleted

[Edited by - Ksingh30 on August 27, 2005 11:52:23 PM]

##### Share on other sites
change this line: return (Sort(a, length-1));
to: return (Sort(a+1, length-1));

though that probably won't compile, so change
this line: int* Sort(int a[], int l)
to: int* Sort(int* a, int l)

this is because a pointer can be used as an array, but an array isn't a pointer, so go with the pointer because it is more versatile. Even better get rid of l, and use a pointer for that too. Do a while != kind of thing.

oh and yeah, if you are going to return something in a recursive function you need at least two return statements. I would just recommend dropping the return entirely.

let's see

void SelectionSort(int* begin, int* end){    int* iter(begin);//iter starts equal to begin    int* largest(begin);//so does largest    while(iter!=end)    {        if( *iter > *largest)            largest=iter;        ++iter;    }    swap(*iter,*largest);//swap is defined in <algorithm>    SelectionSort(begin+1,end);}int a[length];SelectionSort(a,a+length);//here is how you call it

1. 1
2. 2
3. 3
Rutin
15
4. 4
5. 5

• 9
• 9
• 11
• 11
• 23
• ### Forum Statistics

• Total Topics
633679
• Total Posts
3013294
×