//Precondition: none //Postcondition: elements have been sorted using Selection
ID: 3617142 • Letter: #
Question
//Precondition: none
//Postcondition: elements have been sorted using Selection Sortalgorithm
{
comparisons = 0;
movements = 0;
int pos;
int min;
for (int i = 0; i < numberOfElements-1;i++) {
pos = i;
min =elements[i];
// find the positionof the minimum element
for (int j = i; j< numberOfElements; j++) {
comparisons++;
if (elements[j] < min) {
min = elements[j];
pos = j;
}
}
if (i != pos) {
movements += 3;
// exchange values between minimum element and current element
swap(elements[i], elements[pos]);
}
}
ordered = true; // KNOWN to be ordered
}
Explanation / Answer
{
comparisons = 0;
movements = 0;
int pos;
int min;
for (int i = 0; i < numberOfElements-1; i++) {
pos = i; //getting the position of element
min = elements[i]; //first element is considered as min
// find the position of the minimum element
for (int j = i; j < numberOfElements; j++) { //check all the array and find the minimum number
comparisons++;
if (elements[j] < min) { //if any number is less then our already minimum number then now this is our new minimum number which is present in data.
min = elements[j]; //get this number (which is less than min) is new minimum number
pos = j; //saves it position in the array
}
}
if (i != pos) { //checking whether any new minimum number is found or not, if found then its pos previous value which was set equal to i was changed.
movements += 3;
void AList::SelectionSort(int& comparisons, int& movements)
{
comparisons = 0;
movements = 0;
int pos;
int min;
for (int i = 0; i < numberOfElements-1; i++) {
pos = i; //getting the position of element
min = elements[i]; //first element is considered as min
// find the position of the minimum element
for (int j = i; j < numberOfElements; j++) { //check all the array and find the minimum number
comparisons++;
if (elements[j] < min) { //if any number is less then our already minimum number then now this is our new minimum number which is present in data.
min = elements[j]; //get this number (which is less than min) is new minimum number
pos = j; //saves it position in the array
}
}
if (i != pos) { //checking whether any new minimum number is found or not, if found then its pos previous value which was set equal to i was changed.
movements += 3;
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.