Code Excerpt From a C++ Book Showing How to Sort Arrays:
void sort(int array[], int size)
{
for(int i= 0; i < size; i++)
{
int index = findSmallestRemainingElement(array, size, i);
swap(array,i,index);
}
}
int findSmallestRemainingElement(int array[], int size, int index)
{
int index_of_smallest_value = index;
for (int i = index + 1; i < size; i++)
{
if (array[i] < array[index_of_smallest_value])
{
index_of_smallest_value= i;
}
}
return index_of_smallest_value;
}
void swap(int array[], int first_index, int second_index)
{
int temp=array[first_index];
array[first_index] = array[second_index];
array[second_index] = temp;
}
The book did not really explain this part very well, so I am left with a few questions about functions.
What is the difference between the size and index of an array?
The answer to that question will probably help me understand these functions a lot more, but in case it doesn't...
How exactly do the findSmallestRemainingElement(int array[], int size, int index) function and the void swap(int array[], int first_index, int second_index) functions work?
Obviously I know the overall purpose of each function, I just do not understand the line by line of it and the different things the code is doing.
Thank you to anyone who takes the time to help me understand this!
sizeis how big the array is, so e.g.sizefor{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}is10.indexpoints to the element currently being considered. Valid indexes for the array just shown are 0 through 9. As the name suggests,findSmallestElementfinds the index of the element with the smallest value starting with the index passed in. Once that's found,swapexchanges the first element not yet sorted with that, and then the logic proceeds with the next element.intfor array index variables you should throw away.