分类: C/C++
2007-11-10 21:02:40
void BubbleSort(int r[],int n)
{//冒泡排序(有小到大)
int i,j,k;
int exchange;
for(i=0;i<=n;i++)
{
exchange=0;
for(j=n-1;j>=i;j--)
if(r[j+1]
k=r[j+1];
r[j+1]=r[j];
r[j]=k;
exchange=1;
}
if(!exchange)
break;
}
}
2、快速排序
void swap(int &a,int &b) //交换两个数的大小a,b
{
int temp;
temp = a;
a = b;
b = temp;
}
int Partition(int a[],int low,int high)//返回枢纽记录应该放的位置
{
int temp;
int pivotkey = a[low];
while(low < high)
{
while((low < high) && (a[high] >= pivotkey))
--high;
swap(a[low],a[high]);
while((low < high) &&(a[low] <= pivotkey))
++low;
swap(a[low],a[high]);
}
return low;
}
void QSort(int a[],int low,int high)
{
int pivotloc;
if(low < high)
{
pivotloc = Partition(a,low,high);
QSort(a,low,pivotloc-1);
QSort(a,pivotloc+1,high);
}
}
3、选择排序
void SelectSort(int arr[],int len)
{
int i,j;
int minPos,temp;
for(i = 0; i < len - 1; i++)
{
minPos = i;
for(j = i+1; j < len; j++)
{
if(arr[j] < arr[i])
minPos = j;
}
if(minPos != i)
{
temp =arr[minPos];
arr[minPos] = arr[i];
arr[i] = temp;
}
}
}