Problem 1: (Sorting) Write a program that sorts n integers, from smallest to lar
ID: 3835408 • Letter: P
Question
Problem 1: (Sorting) Write a program that sorts n integers, from smallest to largest, with what's called the selection sort method. The input and output should be exactly How many numbers do you have? CUSER ENTERS A POSITIVE INTEGER] Input number (count 1): CUSER ENTERS A INTEGER] Input number (count 2) CUSER ENTERS A INTEGER] Input number (count X): CUSER ENTERS A INTEGER) The sorted input is: x count 1) X (count 2) X (count X) You may not use any libraries aside from iostream and string Hint. There are many ways to sort an array, and some are quite sophisticated. In my opinion, the selection sort method is the simplest (although not the best). We suggest you write your program in the following steps Get the number n from the user. Create a dynamically allocated array of size n Store the numbers in the array. Find the smallest entry among entries o to n-1. Swap the smallest entry with entry o. Le., store the value of the oth int, write the smallest int into the oth spot, and write the stored int into the spot the smallest int used to occupy. Find the smallest entry among entrics 1 to n-1, and swap the smallest entry with entry 1Explanation / Answer
#include <iostream>
using namespace std;
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void selectionSort(int numbers[], int n)
{
int i, j, min_ind;
for (i = 0; i < n-1; i++)
{
min_ind = i;
for (j = i+1; j < n; j++)
{
if (numbers[j] < numbers[min_ind])
{
min_ind = j;
}
}
swap(&numbers[min_ind], &numbers[i]);
}
}
int main()
{
cout << "How many numbers do you have? " << endl;
int n;
cin >> n;
int *numbers = new int [n];
for(int i = 0; i < n; i++)
{
cout << "Input number (count " << (i+1) << "): ";
cin >> numbers[i];
}
selectionSort(numbers, n);
cout << "Sorted numbers: ";
for(int i = 0; i < n; i++)
{
cout << numbers[i] << " ";
}
cout << endl;
delete [] numbers;
return 0;
}