[转贴] C++常用排序算法

来源:互联网 发布:商贸公司淘宝 编辑:程序博客网 时间:2024/05/21 22:46
//选择排序法SelectionSort(int arr[],int n) template void SelectionSort(T arr[],int n) { int smallIndex; //表中最小元素的下标 int pass,j; //用来扫描子表的下标 T temp; //用来交换表元素的临时变量 //pass的范围是0~n-2 for (pass=0;passarr[largeIndex]) largeIndex=j; if(largeIndex!=rightPass) { temp=arr[rightPass]; arr[rightPass]=arr[largeIndex]; arr[largeIndex]=temp; } //从两头收缩子表 leftPass++; rightPass--; } } //自编冒泡法排序算法函数bubbleSort()的实现 template int bubbleSort(T arr[],int n) { bool exchanged=false; //是否发生交换 int i,j; //用于遍历子表的下标 T temp; //用于交换元素的临时变量 //开始遍历过程,以下标j构成子表,共有n-1个子表 for (j=n-1;j>=0;j--) //j从后往前收缩n-1~0,以构成子表0~n-1,0~n-2,0~n-3..0~1 { exchanged=false; for (i=0;iarr[i+1]) { temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; exchanged=true; } } if (!exchanged) return n-j-1;//如果在一次遍历中没有发生交换,则表示已经 //排序好,中断遍历过程 } return n-1-j; } //冒泡法排序一般算法函数bubbleSortEx()的实现 template int bubbleSortEx(T arr[],int n) { int i,pass; //用于遍历子表的下标 T temp; //用于交换元素的临时变量 //开始遍历过程,以下标j构成子表,共有n-1个子表 for (pass=0;passarr[i+1]) { temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } } return pass; }