Write your question here.
Hello everyone I have to write a program that sorts numbers from least to greatest. The way that it has to sort them is:
1) The program assigns the first number to be a minimum
2) If the next number is less than the minimum is now that number and they switch places. (We keep on looking if the number next to it is not smaller)
3) The program also gets the index of the minimum number
4) We keep on going until it is in order.
You may want to search for some documentation for a "Bubble sort" since that seems to be what you're describing in your text. Your implementation doesn't really resemble a sort, yet.
I recommend you make yourself a function to find the index of the smallest number.
int smallest(vector<int>&xs, int start)
The start argument is necessary because there is the sorted part of the array (indices less than start) and the unsorted part (indices from start through length-1).
Now your sort function can loop from 0 to length-1 and simply find the next smallest number in the unsorted part (current index to end).
How would you personally find the smallest number if someone walked up to you with a list of numbers?
You would probably start by looking at the beginning of the list of numbers.
And as you read through all the numbers, you would remember the smallest number you came across and where you saw it. This is pretty much exactly what your 4 point list says in your OP.
Now all that is left is to translate that into code.
And I would do as Duoas suggests and put this smallest search into a function that accepts an index to begin searching from.
If it helps you can imagine that inside the function is your thought process for when somebody walks up to you on the street and hands you a list of numbers. That person also tells you start looking from here because I say so.
int smallest(vector<int>&xs, int start)
{
// must keep two things in memory
// 1. the smallest number I have seen so far
// 2. where I saw the smallest number
int min = /* first element of the list, remember the guy on the street gave a start location */;
int min_index = /* index of the first element of the list (cough start cough) */
// start reading numbers
for(int i = /* where is that guy from the street telling you to start from? */; i <= xs.size() - 1; i++)
{
// check if the number I am reading is smaller than the smallest I have seen so far
if(min > /* current number your eyes are looking at */)
{
// oh it is smaller! time to remember new things!
min = /* current number your eyes are looking at */;
min_index = /* index of the current number your eyes are looking at */;
}
}
//I have finished scanning all the way to the end of the list
//time to give that shady street guy the location of the smallest number that he asked for
return min_index;
}
Edit: just noticed I had the if condition backwards. fixed.