算法笔记——归纳法

归纳法

选择排序

//SelectionSortRec
// input : A[1...n]
// output : 非降序 A[1...n]
1.sort(1)

过程 sort(i)
if (i < n) then
   k = i;
   for(j = i+1; j < n; j++)
      if(A[j] < A[k]) then k = j;
   if(k != i) A[i] <-> A[k];
   sort(i+1);
end if

在这里插入图片描述

插入排序

// InsertionSortRec
// input : A[1...n]
// output : 非降序 A[1...n]

1.sort(n)

过程 sort(i)
if(i > 1) then
  x = A[i];
  sort(i-1);
  j = j - 1;
  while(j > 0 && A[j] > x)
     A[j+1] = A[j];
     j--;
  end while;
  A[j+1] = x;

整数幂

//ExpRec
//input: 实数 x 和非负整数 n

1. power(x,n)

过程 power(x,m)
if(m = 0) then y = 1
else y = power(x, |_m/2_|);
     y = y^2;
     if(m 为奇数) then y = xy;
end if 
return y;
// Exp

y = 1;
将 n 用 dk dk-1 ... d0 表示
for j = k to 0
   y = y^2;
   if(dj = 1) then y = xy;
end for
return y;

寻找多数元素

观察结论: 在原序列中去除两个不同的元素后,那么在原序列中的多数元素在新序列中还是多数元素。 (但是,A[1+2i … n] 中的多数元素未必是 A[1…n] 的多数元素,需要验证。)

// Majority

c = candidate(1);
count = 0;
for j = 1 to n
   if(A[j] = c) count ++;
if(count > |_n/2_|) return c;
else return none;

过程 candidate(m)

j = m , c = A[m], count = 1;
while (j < n  && count > 0)
     j = j + 1;
     if(A[j] = c) count ++;
     else count --;
end while
if (j = n) return c;
else return candidate(j + 1);

例题

数组A[1…n]中存放了n个升序排列的整数,给定整数x,设计一个O(nlogn)的算法,判断数组A中是否存在两个元素的和等于x,如果存在则返回这两个元素的下标;如果不存在返回“Not Exist”。并证明你所设计的算法时间复杂度为O(nlogn).

// Tian'
1. Tian(1)

过程 Tian(m)
if(m < n) then
  i = m;
  k = BinarySearch(X - A[m], m+1 , n);
  if (k != 0) return(i, k);
  else return Tian(m+1);
else return "Not Exist";

复杂度写一个递推式子即可。

猜你喜欢

转载自blog.csdn.net/tian__si/article/details/107916774