如何对冒泡和选择排序,进行结构体数组下标的保存,并且对应输出,(仅数组也行)
给定一个无序数组,规定两两之间不重复,求其中任意一个局部最小值的下标。
#include <iostream>
using namespace std;
struct Person {
string name;
int age;
};
void bubbleSort(Person arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j].age > arr[j + 1].age) {
swap(arr[j], arr[j + 1]);
}
}
}
}
int main() {
Person arr[] = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 20}};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
for (int i = 0; i < n; i++) {
cout << arr[i].name << " " << arr[i].age << endl;
}
return 0;
}
#include <iostream>
using namespace std;
struct Person {
string name;
int age;
};
void selectionSort(Person arr[], int n) {
int i, j, minIndex;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j].age < arr[minIndex].age) minIndex = j;
}
swap(arr[i], arr[minIndex]);
}
}
int main() {
Person arr[] = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 20}};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
for (int i = 0; i < n; i++) {
cout << arr[i].name << " " << arr[i].age << endl;
}
return 0;
}
基于new bing部分指引作答:
在C++中,你可以使用额外的数组来保存冒泡排序或选择排序的数组下标,并输出它们。下面分别给出冒泡排序和选择排序的示例代码:
冒泡排序:
#include <iostream>
void bubbleSort(int arr[], int n) {
int temp;
int indices[n]; // 保存下标的数组
// 初始化indices数组
for (int i = 0; i < n; i++) {
indices[i] = i;
}
// 冒泡排序
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// 交换元素
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
// 交换下标
temp = indices[j];
indices[j] = indices[j+1];
indices[j+1] = temp;
}
}
}
// 输出排序结果及对应的下标
std::cout << "排序结果:";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
std::cout << "下标:";
for (int i = 0; i < n; i++) {
std::cout << indices[i] << " ";
}
std::cout << std::endl;
}
int main() {
int arr[] = {5, 2, 8, 1, 6};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
return 0;
}
选择排序:
#include <iostream>
void selectionSort(int arr[], int n) {
int temp;
int indices[n]; // 保存下标的数组
// 初始化indices数组
for (int i = 0; i < n; i++) {
indices[i] = i;
}
// 选择排序
for (int i = 0; i < n-1; i++) {
int minIndex = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
// 交换元素
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
// 交换下标
temp = indices[i];
indices[i] = indices[minIndex];
indices[minIndex] = temp;
}
}
// 输出排序结果及对应的下标
std::cout << "排序结果:";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
std::cout << "下标:";
for (int i = 0; i < n; i++) {
std::cout << indices[i] << " ";
}
std::cout << std::endl;
}
int main() {
int arr[] = {5, 2, 8, 1, 6};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
return 0;
}
这些示例代码中,我们使用一个叫做indices
的整型数组来保存元素排序前的下标,通过交换元素和下标的方式实现对应关系的保持。最后,我们输出排序结果和对应的下标。希望对你有所帮助!