排序算法练习

来源:互联网 发布:中国网络诗歌 >> 首页 编辑:程序博客网 时间:2024/06/06 02:54

13号看了“查找”。以前也学过,但是也没有很深的印象。如果就是线性表的话,查找还是比较简单的,只需要挨个进行比较,然后逐个后移就可以。如果是链表的话,就要设置一个工作指针。

但是如果涉及到树的查找,就要和遍历有关,得到一个中序遍历,其实就变成了一个顺序排列的线性表。

查找已经排好的数据可以采用二分查找,那样会节省时间,设置两个界限,low,high,并得出mid,用这几个整数来判断是否找到。


今天看了排序,自己编写了一下,参考书上的答案,但是每个开始时候都有问题,经过简单的调试,都得到了正确的答案。

总结:

1.终于学会了在适当的地方添加一定的输出语句,检验程序是否运行到了那个地方。

2.不要一直想着怎么办啊,不对啊,怎么办这样的事情。应该动手分析,到底哪里出现了问题,哪里是可能解决的地方,然后动手解决,这样才能成功。一直停在那想怎么办,对程序的进展是没有任何帮助的。

3.试着把一个大问题分解成多个小问题,然后想想每个小问题需要的是什么,怎么解决每个小问题。然后想想这几个小问题之间的联系,然后把它们全都串联起来,最后就能够顺其自然的解决那个大问题!

直接插入排序:

#include<iostream>
using std::cout;
using std::endl;


void insertsort(int r[],int n)
{
for(int i=1;i<n;i++)
{int j;
r[0]=r[i];//save the present value
for(j=i-1;r[0]<r[j];j--) //when j=0,get out of the circle
r[j+1]=r[j]; 
r[j+1]=r[0];//usually r[1]=r[0],put the smallest in r[1],because r[0] is the guard
}
}


int main()
{
int a[8]={0,12,15,9,20,6,31,24};
insertsort(a,8);


for(int t=1;t<8;t++)
cout<<a[t]<<endl;
}

希尔排序:分成两部分,从后半部分开始排序。

#include<iostream>
using std::cout;
using std::endl;


void shellsort(int r[],int n)
{
int d,i,j;
for(d=n/2;d>=1;d=d/2)
{cout<<"d="<<d<<endl;
for(i=d+1;i<=n;i++)
{
r[0]=r[i];
for(j=i-d;j>0&&r[0]<r[j];j=j-d)//j>0 is a must!
r[j+d]=r[j];//to exchange the value
r[j+d]=r[0];//in the former part, j<d, every time this is excuted
}
for(int p=1;p<=10;p++)
        cout<<r[p]<<"  ";
        cout<<endl;
}
}


int main()
{
int a[]={0,59,20,17,36,98,14,23,83,13,28};
shellsort(a,10);
for(int t=1;t<=10;t++)
cout<<a[t]<<"  ";
cout<<endl;


return 0;
}


冒泡法:

#include<iostream>
using std::cout;
using std::endl;


void bubble(int a[],int n)
{
int i,temp,exchange(n),bound(n);
while(exchange)
{ bound=exchange;//to record where to stop,numbers after bound is already sorted
exchange=0;//this is a must!when there is nothing to change, it is used to get out of the circle.
for(i=0;i<bound;i++)
if(a[i]>a[i+1])//to exchange values, and i+1 must be smaller than 8,since the largest is a[7]!!!
{temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
exchange=i;
}
}
}


int main()
{ int a[]={50,13,55,97,27,38,49,65};//a[0]to a[7]
bubble(a,7);
for(int t=0;t<8;t++) cout<<a[t]<<"  ";
cout<<endl;
return 0;
}

原创粉丝点击