Java数据结构与算法
1.排序
简单排序(第三章)
冒泡排序,选择排序,插入排序
3.1.1冒泡排序
一次循环仅可以排出一个位置
for(out=nElems-1;out>1;out--)
for(int in=0;in<out;in++)
if(a[in]>a[in+1])
{
swap(in,in+1);//long temp=a[in]; a[in]=a[in+1];a[in+1]=temp;
}
交换次数,N2/2 -1
比较次数,N2/2 -1
3.1.2 选择排序
交换次数N
比较次数N2- 1
有序的数据排在左边,
for(out = 0; out < nElems-1 ; out++)
{
min=out;//a[0]作为首位
for(in=out+1;in<nElems;in++)//0位以后与首位比较(不交换)
{
if(a[in]<a[min])
min=in;//更改指针位置
swap(out,min) //首位交换值
}
}
3.1.3 插入排序
for(out=1;out<nElms;out++)
{
long temp=a[out];
in = out;
while(in>0&& a[in-1]>=temp)
{
a[in]=a[in-1];
--in;
}
a[in]=temp;
}
3.1.4 对象排序
3.1.5 递归
int triangle(int n)
{
int total = 0;
while(n>0)
{
total=total+n;
--n;
}
return total;
}
===for===if====
int triangle(int n)
{
if(n==1)
{
System.out.println("Returning 1");
return 1;
}else{
int temp= n+triangle(n-1);//调用本身,方法调用次数过多
System.out.println("Return "+ temp);
return temp;
}
}