冒泡法:冒泡法也叫气泡法排序,它通过将相邻元素进行比较和交换,以从小到大排序为例,将小的调到前头,若有n个数,第一次比较将第1个和第2个数的大小,如果arr[0]>arr[1],就把两个数位置交换;第二次比较第2个数和第3个数的大小……,如此比较(n-1)次,就将最大的数沉到底部,成为arr[n-1],即数组最后一个元素,此过程中会伴随着小的数的“上升”。整个数组排序共经过(n-1)轮后,就将n个数变成了由小--->大的有序序列。
总结:如果有n个数,即数组大小为n,按照这种每轮找出一个最大数沉底的排序方法,共要进行(n-1)轮比较(和交换)。第一轮要进行(n-1)次两两比较,第i轮要进行(n-i)次两两比较。
代码如下:
#include <iostream.h>
#include <conio.h>
#pragma hdrstop
//---------------------------------------------------------------------------
void bubbleSort(double [],int n);
#pragma argsused
int main(int argc, char* argv[])
{
double a[10];
int i;
for (i=0; i<10; i++)
cin>>a[i];
cout<<endl;
bubbleSort(a,10);
for (i=0; i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
getch();
return 0;
}
//---------------------------------------------------------------------------
void bubbleSort(double a[],int n)
{
int i,j;
double temp;
for (i=0; i<n-1;i++) //红色和蓝色的两行效果相同,取其一即可
for (j=0;j<n-(i+1); j++)
for (i=n; i>0;i--)
for (j=0;j<i-1; j++)
if (a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1]=temp;
}
}
选择法:以用选择法对数组中的n个数按由小到大排序为例,首先将n个数中最小的数与arr[0]交换,再将a[1]-a[9]中最小的数与a[1]交换……每比较一轮,找出来未经排序的数中最小的一个。对于arr[n],共比较 (n-1)轮。
代码如下:
#include <iostream.h>
#include <conio.h>
#pragma hdrstop
//---------------------------------------------------------------------------
void SelectSort(double [],int n);
#pragma argsused
int main(int argc, char* argv[])
{
double a[10];
int i;
for (i=0; i<10; i++)
cin>>a[i];
cout<<endl;
SelectSort(a,10);
for (i=0; i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
getch();
return 0;
}
//---------------------------------------------------------------------------
void SelectSort(double a[],int n)
{
int i,j;
int k;
double temp;
for (i=0; i<n-1;i++) //i从0到(n-2),共(n-1)轮
{
k=i;
for (j=i+1; j<n; j++)
if (a[j]<a[k]) //让未经排序中的最小值得元素位置下标赋给k
{
k=j;
}
temp = a[k];
a[k] = a[i];
a[i]=temp;
}
}