10-排序6 Sort with Swap(0, i)

本文介绍了如何使用C++解决数组中元素与索引不匹配的问题,通过定义一个函数findNotOk来寻找第一个不匹配的元素,并通过一系列交换操作将数组调整到期望状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>

void swap(int *a, int *b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}
// int findNotOk(int A[], int N)
int findNotOk(int A[], int begin, int N)// 要从begin开始,从1开始会超时
{
	for (int i = begin; i < N; i++)
		if (A[i] != i)
			return i;
	return 0;
}

int main(int argc, char const *argv[])
{
	// freopen("test.txt", "r", stdin);
	int N;
	scanf("%d", &N);
	int A[N], tmp;
	for (int i = 0; i < N; i++){
		scanf("%d", &tmp);
		A[i] = tmp;
	}
	int cnt = 0;
	int current = findNotOk(A, 1, N);
	while(current != 0){
		if (A[0] == 0){//
			A[0] = A[current];
			A[current] = 0;
			cnt++;
		}
		while (A[0] != 0){
			swap(&A[0], &A[A[0]]);
			cnt++;
		}
		current = findNotOk(A, current, N);
	}
	printf("%d", cnt);
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值