今天开始看谢路云版的数据结构和算法,这本书是结合Java讲的,担心自己因为基础不牢一不小心被语言带跑偏了,所以又下了一本邓俊辉的c++版的,两本书搭配着看,希望能在3月份前看完,并把丢失的记忆找回来,最好还能有点儿新发现。限于电脑上已有软件,为了能快速验证暂用C#记录。
书中提到的第一个算法:冒泡算法
public void BubbleSort(int[] A)
{
int n = A.Length;
while(n > 0)
{
int temp = A[n-1];
for(int i = 0; i < n; i++)
{
if(A[i] > temp)
{
//交换A[i]和temp
A[i] = A[i] ^ temp;
temp = A[i] ^ temp;
A[i] = A[i] ^ temp;
A[n - 1] = temp;
}
}
n--;
}
}
最坏情况时间复杂度为,最好情况为O(n)。
第二道题:对于任意非负整数,计算其二级制展开数中1的个数
int CountBinaryOneCount(int n)
{
int count = 0;
while(n > 0)
{
count += (n & 1);
n >>= 1;
}
return count;
}
时间复杂度为O(logn)
第三道:求n个整数的总和
int SumInt(int[] A)
{
int sum = 0;
for(int i = 0; i < A.Length; i++)
{
sum += A[i];
}
return sum;
}
时间复杂度为O(n)
第四道:在禁止超过1位的移位运算的前提下,对任意非负整数n计算2的n次幂
int PowerTwoN(int n)
{
int result = 1; // 2的0次幂
while(n > 0)
{
result <<= 1;
n--;
}
return result;
}
时间复杂度为O(2(n))