1. 算法步骤
初始化 :将列表分为已排序部分和未排序部分。初始时,已排序部分为空,未排序部分为整个列表。
**查找最小值:**在未排序部分中查找最小的元素。
**交换位置:**将找到的最小元素与未排序部分的第一个元素交换位置。
**更新范围:**将未排序部分的起始位置向后移动一位,扩大已排序部分的范围。
**重复步骤:**重复上述步骤,直到未排序部分为空,列表完全有序。
2.动图

3.代码
#include<iostream>
#include<algorithm>
#include<vector>
#include<cmath>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<string>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<climits>
#include<functional>
#include<numeric>
using namespace std;
int main()
{
int n;
cin >> n;
// Move large array to heap to avoid stack overflow
int* a = new int[n](); // Dynamically allocate memory for the array
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
int wait = 0;
int min = 1000000001, x = 0;
for (int i = 0; i < n; i++)
{
for (int j = wait; j < n; j++) // Fix inner loop to start from 'wait'
{
if (a[j] <= min)
{
min = a[j];
x = j;
}
}
swap(a[wait], a[x]);
wait++;
min = 1000000001; // Reset min for the next iteration
}
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
// Free dynamically allocated memory
delete[] a;
return 0;
}
1028

被折叠的 条评论
为什么被折叠?



