C++排序

来源:互联网 发布:icem网络节点怎么设置 编辑:程序博客网 时间:2024/05/18 01:46

1、插入排序

思想:后面的数和第一个数比较大小进行排序,排序好再后面的数与前两个数进行比较排序,类推……

模板:

template<class T>void InsertionSort(T A[],int n){int i,j;T temp;for(i=1;i<n;i++){j=i;temp=A[i];while(j>&&temp<A[j-1]){A[j]=A[j-1];j--;}A[j]=temp;}}

2、选择排序

思想:将第一个数和后面的每个数进行比较,如果后面的比前面小,就两个数调换位置,最后就将最小的数放在最前面。

template<class T>void Swap(T& x,T& y){T temp;temp=x;x=y;y=temp;}template<class T>void SelectionSort(T A[],int n){int smallIndex;int i,j;for(i=0,i<n-1;i++){smallIndex=i;for(j=i+1;j<n;j++)if(A[j]<A[smallIndex])samllIndex=j;Swap(A[i],A[smallIndex]);}}

3、冒泡排序

思想:从第一个数开始,往下每两个数进行比较,如果后面闭前面小,就调换位置,这样一趟下来就将最大的放到最后。(速度比选择排序要快)

template<class T>void Swap(T& x,T& y){T temp;temp=x;x=y;y=temp;}template<class T>void BubbleSort(T A[],int n){int i,j;int lastExchangeIndex;i=n-1;while(i>0){lastExchangeIndex=0;for(j=0;j<i;j++)if(A[j+1]<A[j]){Swap(A[j],A[j+1]);lastExchangeIndex=j;}i=lastExchangeIndex}}



0 0
原创粉丝点击