1.冒泡排序
方法1
#include <iostream>
using namespace std;
int main()
{
int a[10] = { 9,7,6,4,10,8,5,3,1,2 };
int i, j;
int t;
int length = sizeof(a)/sizeof(a[0]); //获取数组长度
for (i = 0; i <= length - 1; i++)
{
for (j = 0; j <= length - 2; j++) //若为length-1数组越界
{
if (a[j] > a[j + 1])
{
t = a[j + 1];
a[j + 1] = a[j];
a[j] = t;
}
}
}
for (i = 0; i <= length - 1; i++)
{
cout << a[i] << endl;
}
return 0;
}
方法2(每遍历一遍判断是否排序完成,能够提前结束)
#include <iostream>
using namespace std;
int main()
{
int a[10] = { 9,7,6,4,10,8,5,3,1,2 };
int i, j;
int t;
int length = sizeof(a)/sizeof(a[0]); //获取数组长度
bool flag = false;
for (i = 0; i <= length - 1 && !flag; i++)
{
flag = true;
for (j = 0; j <= length - 2; j++) //若为length-1数组越界
{
if (a[j] > a[j + 1])
{
t = a[j + 1];
a[j + 1] = a[j];
a[j] = t;
flag = false;
}
}
}
for (i = 0; i <= length - 1; i++)
{
cout << a[i] << endl;
}
return 0;
}
方法3(在每次排序后会有最大值出现在该次排序的末尾,此最大值不参与下一次的排序;可能一次会排好最大值和第二大值等,故设置upto=j而不是n--)
#include <iostream>
using namespace std;
int main()
{
int a[10] = { 9,7,6,4,10,8,5,3,1,2 };
int i, j;
int t;
int length = sizeof(a)/sizeof(a[0]); //获取数组长度
int n = length - 1;
int upto = 0;
for (i = 0; i <= length - 1; i++)
{
for (j = 0; j <= n - 1; j++) //若为length数组越界
{
if (a[j] > a[j + 1])
{
t = a[j + 1];
a[j + 1] = a[j];
a[j] = t;
upto = j;
}
}
n = upto;
}
for (i = 0; i <= length - 1; i++)
{
cout << a[i] << endl;
}
return 0;
}
方法4(每次循环排序好最大值最小值,并判断没有排序号的范围以进行下次循环排序的优化)
#include <iostream>
using namespace std;
int main()
{
int a[10] = { 9,7,6,4,10,8,5,3,1,2 };
int i;
int length = sizeof(a)/sizeof(a[0]); //获取数组长度
int first = 0;
int last = length - 1;
int t;
while (first < last)
{
int nfirst = first, nlast = last;//用于判断循环中有无变换以及未排序好的范围
for (i = first; i <= last - 1; i++) //正向循环
{
if (a[i] > a[i + 1])
{
nlast = i;
t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
}
}//将最大值排到最后
if (nlast == last) //若此次循环没发生变换即排序完成
{
break;
}
last = nlast;
for (i = last; i >= first + 1; i--) //逆向循环
{
if (a[i] < a[i - 1])
{
nfirst = i;
t = a[i];
a[i] = a[i - 1];
a[i - 1] = t;
}
}
if (nfirst == first) //若此次循环没发生变换即排序完成
{
break;
}
first = nfirst;
}
for (i = 0; i <= length - 1; i++)
{
cout << a[i] << endl;
}
return 0;
}
2.选择排序