王道数据结构课后习题p18(1.10-1.12)

10.将整数存放到一维数组R中,将R中保存的循环序列左移p个位置,即将r中数据由(x0, x1, ..., xn-1)变换为(xp, xp+1, ..., xn-1, x0, x1, ..., xp-1)

//算法思想:将(x0, x1, ..., xp-1, xp, xp+1, ..., xn-1)转换为(xp, xp+1, ..., xn-1, x0, x1, ..., xp-1)
void reverse(int x[], int from, int to) {
	int m = (to - from + 1) / 2;
	for (int i = 0; i < m;i++) {
		ElemType temp = x[from + i];
		x[from + i] = x[to - i];
		x[to - i] = temp;
	}
}
void exchange(DataType x[], int p, int n) {
	reverse(x, 0, n - 1);
	reverse(x, 0, p - 1);
	reverse(x, p, n - 1);
}

11.长度为L的升序序列S,第L/2个位置的数称为S的中位数,有两个等长升序序列A和B,找出两个序列A和B的中位数

//算法思想:设A的中位数为a,B的中位数为b,若a=b,则相等,若a<b,舍弃A中较小的一半,若a>b,舍弃B中较大的一半
int  M_search(int A[], int B[], int n) {
	int s1 = 0, d1 = n - 1, m1, s2 = 0, d2 = n - 1, m2;
	//s代表首位数,d代表末位数,m代表中位数
	while (s1 != d1 || s2 != d2) {
		m1 = (s1 + d1) / 2;
		m2 = (s2 + d2) / 2;
		if (A[m1] == B[m2])
			return A[m1];
		if (A[m1] < A[m2]) {
			if ((s1 + d1) % 2 != 0) {
				s1 = m1;
				d2 = m2;
			}
			else {
				s1 = m1 + 1; //舍弃A中间点以及中间点以前的部分
				d2 = m2; //舍弃B中间点以后的部分且保留中间点
			}
		}
		else {
			if ((s1 + d1) % 2 != 0) {
				d1 = m1;
				s2 = m2;
			}
			else {
				d1 = m1;
				s2 = m2 + 1;
			}
		}
	}
	return A[s1] < B[s2] ? A[s1] : B[s2]; 
}

12.已知一整数系列A,若存在ap1=ap2=...=apm=x且m>n/2;则称x为A的主元素。假设A中的n个元素保存在一个一维数组中,找出A的主元素,若没有,则返回-1

int Majority(int A[], int n) {
	int i, c, count = 1; //用c来保存候选主元素
	c = A[0]; //设置A[0]为候选主元素
	for (i = 1;i < n;i++) { //查找候选主元素
		if (A[i] == c) count++; // 计数
		else {
			if (count > 0) count--; //不是候选主元素的情况
			else { //更换候选主元素,重新计数
				c = A[i];
				count = 1;
			}
		}
	}
	if (count > 0)
		for (i = count = 0;i < n;i++) //统计候选主元素的出现次数
			if (A[i] > 0) count++;
	if (count > n / 2) return c; //确认候选主元素
	else return -1;
}

猜你喜欢

转载自blog.csdn.net/weixin_42341986/article/details/80538786