#include <iostream> using namespace std; void selectionSortArray(int [], int); v
ID: 3904141 • Letter: #
Question
#include <iostream>
using namespace std;
void selectionSortArray(int [], int);
void displayArray(int[], int);
int main()
{
int data[] = {9, 2, 0, 11, 5, 43, 22, 3, 102, 17, -3};
int size = 11;
cout << "The values before the selection sort is performed are:" << endl;
displayArray(data, size);
selectionSortArray(data, size);
cout << "The values after the selection sort is performed are:" << endl;
displayArray(data,size);
system("pause");
return 0;
}
void displayArray(int array[], int length)
{
for (int count = 0; count < length; count++)
cout << array[count] << " ";
cout <<endl;
}
void selectionSortArray(int list[], int length)
{
int seek;
int minCount;
int minValue;
for (seek = 0; seek < (length-1);seek++)
{
minCount = seek;
minValue = list[seek];
for(int index = seek + 1; index < length; index++)
{
if(list[index] < minValue)
{
minValue = list[index];
minCount = index;
}
}
list[minCount] = list[seek];
list[seek] = minValue;
}
}
Rewrite function selectedSortArray so that finding the index of the smallest element in the remainder of the list is done by a separate function. The definition of selectionSortArray function should be as following:
int getIndexOfMin(int list[], int first, int length)
/* function takes an array of int of size length and returns the index of the smallest element between positions first and length -1.
*/
{
// Complete function body here
}
void mySwap(int list[], int index1, int index2)
/* function swaps element at position index1 in array list with element at position index2 */
{
// Complete function body here
}
void selectionSortArray(int list[], int length)
{
int seek; // array position currently being put in order
int indexOfMin; // location of smallest value found
int minValue; // holds the smallest value found
for (seek = 0; seek < (length-1);seek++) // outer loop performs the swap
// and then increments seek
{
indexOfMin = getIndexOfMin(list, seek, length);
mySwap(list, seek, indexOfMin);
}
}
Explanation / Answer
int getIndexOfMin(int list[], int first, int length)
/* function takes an array of int of size length and returns the index of the smallest element between positions first and length -1. */
{
int indexOfMin = first;
int index;
for(index = first+1; index < length; index++)
{
if(list[index] < list[indexOfMin])
{
indexOfMin = index;
}
}
return indexOfMin;
}
void mySwap(int list[], int index1, int index2)
/* function swaps element at position index1 in array list with element at position index2 */
{
int temp = list[index1];
list[index1] = list[index2];
list[index2] = temp;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.