轻松掌握C++排序算法---选择排序

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值