Sign in to follow this  

selection sort

This topic is 2852 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[i]=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
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
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

This topic is 2852 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this