I need this implementation of the selection sort to be applied on a code to run
ID: 3583040 • Letter: I
Question
I need this implementation of the selection sort to be applied on a code to run it on C++. I need then to see what came out in the output
------------------------------------------------------------------------------------------------------------------------
/** Finds the largest item in an array.
@pre The size of the array is >= 1.
@post The arguments are unchanged.
@param theArray The given array.
@param size The number of elements in theArray.
@return The index of the largest entry in the array. */
int findIndexofLargest(const ItemType theArray[], int size);
/** Sorts the items in an array into ascending order.
@pre None.
@post The array is sorted into ascending order; the size of the array
is unchanged.
@param theArray The array to sort.
@param n The size of theArray. */
void selectionSort(ItemType theArray[], int n)
{
// last = index of the last item in the subarray of items yet
// to be sorted;
// largest = index of the largest item found
for (int last = n - 1; last >= 1; last––)
{
// At this point, theArray[last+1..n-1] is sorted, and its
// entries are greater than those in theArray[0..last].
// Select the largest entry in theArray[0..last]
int largest = findIndexofLargest(theArray, last + 1);
// Swap the largest entry, theArray[largest], with
// theArray[last]
std::swap(theArray[largest], theArray[last]);
} // end for
} // end selectionSort
int findIndexofLargest(const ItemType theArray[], int size)
{
int indexSoFar = 0; // Index of largest entry found so far
for (int currentIndex = 1; currentIndex < size; currentIndex++)
{
// At this point, theArray[indexSoFar] >= all entries in
// theArray[0..currentIndex - 1]
if (theArray[currentIndex] > theArray[indexSoFar])
indexSoFar = currentIndex;
} // end for
return indexSoFar; // Index of largest entry
} // end findIndexofLargest
Explanation / Answer
#include<iostream>
using namespace std;
int main()
{
int i,j,n,loc,temp,min,a[30];
cout<<"Enter the number of elements:";
cin>>n;
cout<<" Enter the elements ";
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n-1;i++)
{
min=a[i];
loc=i;
for(j=i+1;j<n;j++)
{
if(min>a[j])
{
min=a[j];
loc=j;
}
}
temp=a[i];
a[i]=a[loc];
a[loc]=temp;
}
cout<<" Sorted list is as follows ";
for(i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<" Largest Number : "<<a[n-1];
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int i,j,n,loc,temp,min,a[30];
cout<<"Enter the number of elements:";
cin>>n;
cout<<" Enter the elements ";
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n-1;i++)
{
min=a[i];
loc=i;
for(j=i+1;j<n;j++)
{
if(min>a[j])
{
min=a[j];
loc=j;
}
}
temp=a[i];
a[i]=a[loc];
a[loc]=temp;
}
cout<<" Sorted list is as follows ";
for(i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<" Largest Number : "<<a[n-1];
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.