运行结果:
Enter numbers: 0 -3.45 -1 -66 100 32.32 54.12 9.99 8.09 -6.66 -3.44 -1 1.99 -1 0 9 p
Ascending sort: -66 -6.66 -3.45 -3.44 -1 -1 -1 0 0 1.99 8.09 9 9.99 32.32 54.12 100
Descending sort: 100 54.12 32.32 9.99 9 8.09 1.99 0 0 -1 -1 -1 -3.44 -3.45 -6.66 -66
selectionSort.cpp
#include <iostream>
#include <cctype>
// double ar[]表示参数为数组指针,可用 double* ar 替换,两者功能相同。
double* fillArray(double ar[], int&, int&);
double* autoIncreaseArray(double*, int&);
void selectionSortAscending(double ar[], int len);
int smallestValue(double ar[], int len, int startIndex);
void selectionSortDescending(double ar[], int len);
int maxValue(double ar[], int len, int startIndex);
void swapValue(double&, double&);
void show(double*, int);
void copyAr(double*, double*, int);
int main() {
using std:: cout;
using std:: cin;
int size = 10, usedSize = 0;
double* ar = new double[size]; // 默认数组长度为 10,根据实际输入数据量自动调整数组大小
cout << "Enter numbers: ";
ar = fillArray(ar, size, usedSize); // size 表示数组总长, usedSize 表示实际输入数据个数
selectionSortAscending(ar, usedSize);
cout << "Ascending sort: ";
show(ar, usedSize);
selectionSortDescending(ar, usedSize);
cout << "Descending sort: ";
show(ar, usedSize);
delete [] ar;
return 0;
}
double* fillArray(double ar[], int& size, int& usedSize) {
using std:: cin;
double tmp;
double* inAr = ar;
while (true) {
if (! (cin >> tmp)) // 当 tmp 读取的数据非数字时,结束循环
break;
if (usedSize >= size) {
ar = autoIncreaseArray(inAr, size);
delete [] inAr;
inAr = ar;
}
ar[usedSize] = tmp;
usedSize++;
}
return ar;
}
double* autoIncreaseArray(double* ar, int& size) {
double* inAr = new double[size * 2];
copyAr(inAr, ar, size);
size *= 2;
return inAr;
}
void selectionSortAscending(double ar[], int len) {
int index;
for (int i = 0; i < len; i++) {
index = smallestValue(ar, len, i);
if (ar[i] != ar[index])
swapValue(ar[i], ar[index]);
}
}
int smallestValue(double ar[], int len, int startIndex) {
for (int i = startIndex + 1; i < len; i++) {
if (ar[i] < ar[startIndex])
startIndex = i;
}
return startIndex;
}
void selectionSortDescending(double ar[], int len) {
int index;
for (int i = 0; i < len; i++) {
index = maxValue(ar, len, i);
if (ar[i] != ar[index])
swapValue(ar[i], ar[index]);
}
}
int maxValue(double ar[], int len, int startIndex) {
for (int i = startIndex + 1; i < len; i++) {
if (ar[i] > ar[startIndex])
startIndex = i;
}
return startIndex;
}
void swapValue(double& big, double& small) {
double tmp = big;
big = small;
small = tmp;
}
void copyAr(double* inAr, double* ar, int size) {
for (int i = 0; i < size; i++)
inAr[i] = ar[i];
}
void show(double* ar, int len) {
for (int i = 0; i < len; i++) {
std::cout << ar[i] << " ";
}
std::cout << "\n";
}