编程之美1.2

prefixSort.cpp
#include<iostream>
#include<assert.h>
using namespace std;

int cakeCount;//用于存储一共有多少个cake
int uperBound;
int *cakeArray;//保存初始cake排列的情况
int *cakeSwapArray;//保存对cake进行翻转得到的临时Array情况
int *swapNumArray;//保存每次翻转的第几个cake(按照数组的顺序)
int *swapNumArrayTemp;
void reverse(int *a, int cur){//交换第cur位
	int length = cur + 1;
	assert(a != NULL);
	assert(length > 0);
	for (int i = 0; i < length/2; i++){
		int temp = a[i];
		a[i] = a[length - i - 1];
		a[length - i - 1] = temp;
	}

}
int lowerBound(int *a, int length){
	int reverseCount = 0;
	for (int i = 1; i<length; i++){
		int t = a[i - 1] - a[i];
		if (t == 1 || t == -1){
			;
		}
		else{
			reverseCount++;
		}
	}
	return reverseCount;
}
bool isSorted(int *a, int length){
	assert(a != NULL);
	assert(length > 0);
	for (int i = 1; i < length; i++){
		if (a[i] - a[i - 1] != 1){
			return false;
		}
	}
	return true;
}
void init(int *a, int length){
	cakeCount = length;
	cakeArray = new int[length];
	cakeSwapArray = new int[length];
	for (int i = 0; i < length; i++){
		cakeArray[i] = a[i];
		cakeSwapArray[i] = a[i];
	}
	uperBound = 2 * cakeCount;//初始化最大的上界限
	swapNumArray = new int[uperBound];
	swapNumArrayTemp = new int[uperBound];
}
void printArray(int *a, int length){
	assert(a != NULL);
	assert(length > 0);
	for (int i = 0; i < length; i++){
		printf("%d  ", a[i]);
	}
	printf("\n");
}
void search(int step){
//	cout << "uperBound:" << uperBound << endl;
	
	if (step > uperBound){
		return;
	}
	if (isSorted(cakeSwapArray, cakeCount)){
		if (uperBound > step){
			uperBound = step;
			for (int i = 0; i < step; i++){
				swapNumArrayTemp[i] = swapNumArray[i];
			}
		}
		return;
	}
	for (int i = 1; i < cakeCount; i++){
//		cout << "i:"<<i << endl;
		reverse(cakeSwapArray, i);
//		cout << "step:" << step << endl;
		swapNumArray[step] = i;		
		search(step + 1);
		reverse(cakeSwapArray, i);
	}
}
int main(){
	int a[8] = {2,7,5,6,4,0,3,1};
	init(a, 8);
//	printArray(a, 3);
//	reverse(a, 1);
//	printArray(a,3);
	search(0);
	for (int i = 0; i < uperBound; i++){
		cout << swapNumArrayTemp[i] << " ";
	}
	cout << endl;
	cout <<"uperBound:"<< uperBound << endl;
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值