Jump to content
  • Advertisement
Sign in to follow this  
phil67rpg

selection sort

This topic is 3163 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

I am trying to program a selection sort routine, here is my code
#include <iostream>

using namespace std;

int main()
{
	int integers,swap;
	int array[10];
	cout << "Enter ten unsorted integers..." << endl;
	
	for (int i=0;i<10;i++)
	{
	cout << "[" << i << "] = ";
	cin >> integers;
	array=integers;
	}
	
	cout << "Unsorted List = ";

	for (int j=0; j<10; j++)
	{
	cout << array[j] << ", " ;
	}
	cout << endl;
	cout << "Sorting..." << endl;

	cout << "Sorted List = ";
	
	for(int k=0;k<10;k++)
	{
	if(array[k+1] < array[k])
	{
	swap=array[k+1];
	array[k+1]=array[k];
	array[k]=swap;
	}
	cout << array[k] << ", ";

	}
	cout << endl;

	return 0;
}

Share this post


Link to post
Share on other sites
Advertisement
Bubble sort; you need to iterate through the array until all elements satisfy arrayN < arrayN+1.

EDIT:
Ninja'd x3. Look at your for-loop code carefully, if array has elements indexed from 0 to 9, then this loop:


for(int k=0;k<10;k++)
if(array[k+1] < array[k])



What is k+1 when k is 9?

Share this post


Link to post
Share on other sites
Looks more like bubble sort to me.

You're only making one pass. You need to keep doing your swap loop until you don't detect any swaps.

Share this post


Link to post
Share on other sites
It would be Bubble Sort if it weren't for the fact that there are no nested loops, and there's an of-by-one error.
How about looking up the source code for the algorithm of your choice from Wikipedia?

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!