Public Group

# 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.

## 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 on other sites
So what's your question?

And?

##### Share on other sites
well I get an "out of bounds" error, this is a run time error.

##### 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 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 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?

1. 1
Rutin
47
2. 2
3. 3
4. 4
5. 5

• 13
• 10
• 12
• 10
• 13
• ### Forum Statistics

• Total Topics
632993
• Total Posts
3009758
• ### Who's Online (See full list)

There are no registered users currently online

×