Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

#include \"stdafx.h\" #include <iostream> #include <iomanip> using namespace std

ID: 3586959 • Letter: #

Question

#include "stdafx.h"

#include <iostream>

#include <iomanip>

using namespace std;

#define entries 20

int main() {

int i, v, j, k;

int a = 0;

int list1[entries], list2[entries];

for (i = 0, j = 0; i<entries; i++, j += 1299827) {

v = (j % 1024);

list1[i] = v; list2[i] = v;

cout << i << " " << list1[i] << " " << list2[i] << endl;

}

for (i = 0; i<entries; i++) {

if (list2[i] >= a) {

a = list2[i];

k = i;

}

}

cout << "The index with the highest value is " << k << endl;

cout << endl << "Swapping highest value with value in first index in list2.." << endl << endl;

//..... .. swap......

//if highest value index is not first index

if (k != 0) {

int temp = list2[k];

list2[k] = list2[0];

list2[0] = temp;

}

//.........end swap.....

cout << "list2 after swapping: ";

for (i = 0; i<entries; i++) {

cout << i << " " << list2[i] << endl;

}

}

At this point the first element in list2 should be the highest but all the other elements are unsorted. To completely sort of all elements in the list we do the same operation as we did before but we start at the second item. Again we use our flag to indicate that this is the largest value and search the remaining items to see if any of those are larger. If this is the case, we update our flag and move on. When this loop is done, we swap the largest element with the second one in the list and now our list has the two largest items at the top of the list. We continue to do this until we are on the second last item. Our loop at this point will only compare it to the last, and will swap them if necessary. This approach is called a “selection sort” since we are selecting the largest item in our list and moving it to the beginning of our list. To code this we need two nested loops. The outer loop will go from the first to the second last elements (0 to entries-2 inclusively). Inside this loop you will place your code for searching for and swapping the largest value. Be careful to change the references from the first element, 0, to the value of the outer loop counter. Your inner loop should go from the current outer loop element plus 1 to the last (entries-1) inclusively. Write your code below that does this:

Explanation / Answer

selection sort code

void swapElements(int *a, int *b)

{

int c = 0;

c = *a;

*a = *b;

*b = c;

}

void sorting(int array[], int len)

{

int k, j, minIndex;

for (k = 0; k < len-1; k++)

{

minIndex = k;

for (j = k+1; j < len; j++)

if (array[j] < array[minIndex])

minIndex = j;

swap(&array[minIndex], &array[k]);

}

}