哪位高手帮我写一个C++冒泡排序算法代码?(加注解)
希望高手帮我写一个好吗?
void bubble(int n, int *a)
{
int i = j =0;
int temp;
j = n - 1;
while (i != j)
{
for (i=0; i<j; i++)
{
if (a[i] > a[i+1])
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
j--;
}
}
eg:
5 3 4 2
3 5 4 2
3 4 5 2
3 4 2 5
3 2 4 5
2 3 4 5
void sort(double *x,int n)
{
int i,j,k;
double t;
for(i=0;i<n-1;i++)
{
k=i;
for(j=i+1;j<n;j++)
if(*(x+j)>*(x+k)) k=j;
if(k!=i)
{ t=*(x+i); *(x+i)=*(x+k); *(x+k)=t; }
}
}
太长非法贴自己到
http://algorithm.myrice.com/algorithm/commonalg/sort/internal_sorting/bubble_sort/bubble_sort.htm
下看
void main(void)
{
int dat[255],i,j,temp,number=0;//data存放要排序的数据。
//number为数据的个数。
//输入数据;
for(j = 0;j<number-1;j++)//比较number-1次
{
for(i = 0;i<number-1;i++)
{
if(data[i]<data[i+1])//交换顺序
{
temp = data[i];
data[i] = data[i+1];
data[i+1] = temp;
}
}
}
//输出
}
template <typename elemType>
void Sort(elemType * ptrArr,int size,bool (* Biger)(elemType frst,elemType scnd))
{
bool flgNoChange(false);
int n;
elemType temp;
while (!flgNoChange)
{
flgNoChange=true;
for(n=0;n<size-1;n+)
{
if(Biger(ptrArr[n],ptrArr[n+1]))
{
temp=ptrArr[n];
ptrArr[n]=ptrArr[n+1];
ptrArr[n+1]=temp;
flgNoChange=false;
}
}
}
}
这段程序可以对任何类型的数组做冒泡排序,由于数组类型不能确定,
所以比较规则由一个函数指针传进来,作为一个参数.调用者可以自己
定义数组类型,通过重载比较规则实现排序.这也是泛型编程的思想.
Sorry.
上面的"for(n=0;n<size-1;n+)"少了一个"+".
: P.笔误,不好意思.
#include <iostream>
#include <cstdlib>
using namespace std;
void bubble_sort(int*,int*);
int main()
{ const int size=10;
int array[size]={2,54,6,8,7,63,9,321,654,32};
int i;
for(i=0;i<size;++i) cout<<array[i]<<' ';
cout<<endl;
bubble_sort(array,array+size);
for(i=0;i<size;++i) cout<<array[i]<<' ';
cout<<endl;
system("PAUSE");
return 0;
}
void bubble_sort(int*first,int*end)
{
int *p1,*p2,t;
for(;end>first;end=p2){
for(p1=p2=first;p1!=end-1;++p1){
if(*p1>*(p1+1)){
t=*p1;
*p1=*(p1+1);
*(p1+1)=t;
p2=p1+1;
}
}
}
}