Jump to content
  • Advertisement
Sign in to follow this  
Ksingh30

Selection Sort

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!