Problem 2: Implement another C++ program to sort a list of integers using the se
ID: 3669619 • Letter: P
Question
Problem 2: Implement another C++ program to sort a list of integers using the selection sort algorithm. You are required to
use an integer vector to store the input numbers typed from the keyboard. The declaration of this vector will be in main(). You'll need to implement a separate function readData() to read numbers from the keyboard;
implement a separate function called selectionSort(), which will be called by the main() function to sort the afore-mentioned vector;
implement another function printVector() to print out the content of the vector. This function will be called by main() right after calling readData() and selectionSort(), respectively, to print out the vector content before and after being sorted.
Explanation / Answer
#include <iostream>
#include <vector>
#include <queue>
#include<cstdlib>
using namespace std;
void swap(std::vector<int> & data, int i, int j)
{
int tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
void print(std::vector<int> const & data)
{
std::vector<int>::const_iterator iter = data.begin();
for (; iter != data.end(); ++iter)
{
cout << *iter << " ";
}
if (data.size() > 0)
{
cout << endl;
}
}
void SelectionSort(std::vector<int> & data)
{
int length = data.size();
for (int i = 0; i < length; ++i)
{
int min = i;
for (int j = i+1; j < length; ++j)
{
if (data[j] < data[min])
{
min = j;
}
}
if (min != i)
{
swap(data, i, min);
}
}
}
int main()
{
int a[] = {5, 6, 1, 2, 0, 8, -1, -2, 8, 0};
std::vector<int> data(a, a + sizeof(a)/sizeof(int));
//Selection sort
//Shuffle(data);
cout<<" Before Sorting ";
print(data);
SelectionSort(data);
cout<<" After Sorting ";
print(data);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.