当循环下标从 1 开始且不使用 a[0] 时,以下是选择排序、冒泡排序和插入排序的代码示例:
#include <iostream>
// 选择排序
void selectionSort(int* a, int size) {
for (int i = 1; i < size - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (a[j] < a[minIndex]) {
minIndex = j;
}
}
if (a[minIndex] < a[i]) {
int temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
}
}
// 冒泡排序
void bubbleSort(int* a, int size) {
for (int i = 1; i < size - 1; i++) {
for (int j = 1; j < size - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
// 插入排序
void insertionSort(int* a, int size) {
for (int i = 2; i < size; i++) {
int key = a[i];
int j = i - 1;
while (j > 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
}
int main() {
int n;
std::cout << "Enter the number of elements: ";
std::cin >> n;
int* arr1 = new int[n+1]; // 选择排序用
int* arr2 = new int[n+1]; // 冒泡排序用
int* arr3 = new int[n+1]; // 插入排序用
std::cout << "Enter " << n << " elements: ";
for (int i = 1; i <= n; i++) {
std::cin >> arr1[i];
arr2[i] = arr1[i];
arr3[i] = arr1[i];
}
selectionSort(arr1, n+1);
bubbleSort(arr2, n+1);
insertionSort(arr3, n+1);
std::cout << "Selection Sorted array: ";
for (int i = 1; i <= n; i++) {
std::cout << arr1[i] << " ";
}
std::cout << std::endl;
std::cout << "Bubble Sorted array: ";
for (int i = 1; i <= n; i++) {
std::cout << arr2[i] << " ";
}
std::cout << std::endl;
std::cout << "Insertion Sorted array: ";
for (int i = 1; i <= n; i++) {
std::cout << arr3[i] << " ";
}
std::cout << std::endl;
delete[] arr1;
delete[] arr2;
delete[] arr3;
return 0;
}