Sort with Swap(0,*) (25)

IDEA

1.注意输入的数字从0-n-1,意思是让数字存在其对应下标下

2.题目只让0和某数交换,交换次数尽量少,则尽量让该数放在正确位置下,完后就不参与交换了

3.考虑两种情况:array[0]==0,0本身在正确位置,若还有不在正确位置的数字,则0与其交换;

array[0]!=0,让通过交换使得array[0]到正确位置,指导位置0有正确数,即0.位置;然后重复第一种情况


IDEA

#include<iostream>
#include<fstream>
using namespace std;
int findpos(int* array,int begin,int end){
	for(int i=begin;i<end;i++){
		if(array[i]!=i){
			return i;
		}
	}
	return 0;
}
//void output(int *array,int n){
//	for(int i=0;i<n;i++){
//		cout<<array[i]<<" ";
//	}
//}
int main(){
	#ifndef ONLINE_JUDGE
	freopen("input.txt","r",stdin);
	#endif
	
	int n;
	cin>>n;
	int *array=new int[n];
	for(int i=0;i<n;i++){
		cin>>array[i];
	}
	int index=1;
	index=findpos(array,index,n);
	int count=0;
	while(index){//index!=0,表示还有没有归为的数 
		if(array[0]==0){
			//swap
			array[0]=array[index];
			array[index]=0;
//			output(array,n);
//			cout<<endl;
			count++;
		}
		while(array[0]!=0){//不在正确位置上,那要通过变换使得v[0] == 0
			int tmp=array[0];
			array[0]=array[tmp];
			array[tmp]=tmp;
//			output(array,n);
//			cout<<"-"<<endl;
			count++;
		}
		index=findpos(array,index,n);//0在自己位置上,找到第一个不在正确位置上的数 
	}
	cout<<count<<endl;
	#ifndef ONLINE_JUDGE
	fclose(stdin);
	#endif
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值