Problem Description
Given multiple batches of data as input, sort each batch in ascending order and output the results.
Each line of input represents one batch of data. The format consists of:
- A data type indicator (1 for integers, 2 for characters, 3 for floating-point numbers with one decimal place, 4 for strings, 0 to terminate)
- The number of elements in this batch (size, where 0 < size ≤ 10)
- The actual data elements of the specified type
Function Interface
The sort template function should accept an array pointer and size parameter, sort the elements in ascending order, and store them back in the original contiguous memory location pointed to by a.
template <class T>
void sort(T *a, int size);
Solution
The implementation uses the selection sort algorithm, which repeatedly finds the minimum element from the unsorted portion and swaps it with the first unsorted element.
template <class T>
void sort(T *arr, int len)
{
// Read input data into the array
for (int idx = 0; idx < len; ++idx) {
cin >> arr[idx];
}
// Selection sort algorithm
for (int i = 0; i < len; ++i) {
int minIndex = i;
for (int j = i + 1; j < len; ++j) {
if (arr[minIndex] > arr[j]) {
minIndex = j;
}
}
if (minIndex != i) {
T temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
}
Complete Example
#include <iostream>
#include <string>
using namespace std;
template <class T>
void sort(T *arr, int len)
{
for (int idx = 0; idx < len; ++idx) {
cin >> arr[idx];
}
for (int i = 0; i < len; ++i) {
int minIndex = i;
for (int j = i + 1; j < len; ++j) {
if (arr[minIndex] > arr[j]) {
minIndex = j;
}
}
if (minIndex != i) {
T temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
}
template <class T>
void display(T* arr, int len) {
for (int i = 0; i < len - 1; ++i) {
cout << arr[i] << ' ';
}
cout << arr[len - 1] << endl;
}
int main() {
const int MAX_SIZE = 10;
int intArray[MAX_SIZE];
char charArray[MAX_SIZE];
double doubleArray[MAX_SIZE];
string stringArray[MAX_SIZE];
int type, size;
cin >> type;
while (type > 0) {
cin >> size;
switch (type) {
case 1:
sort(intArray, size);
display(intArray, size);
break;
case 2:
sort(charArray, size);
display(charArray, size);
break;
case 3:
sort(doubleArray, size);
display(doubleArray, size);
break;
case 4:
sort(stringArray, size);
display(stringArray, size);
break;
}
cin >> type;
}
return 0;
}
Input/Output Example
Input:
1 3 3 2 1
2 2 a A
3 3 1.5 2.6 2.2
4 2 bca abc
0
Output:
1 2 3
A a
1.5 2.2 2.6
abc bca