选择排序(O(m*n))

//简单选择排序
#include<cstdio>
int main(int argc, char const *argv[])
{
int A[6] ={0, 5, 2, 4, 2, 1};
int n = 5;
for (int i = 1; i <= n; ++i) //进行n趟操作
{
int k = i;
for (int j = i; j <= n; ++j) //选出[i,n]中最小的元素,下标为k
{
if(A[j] < A[k]){
k = j;
}
}
int temp = A[i]; //交换A[k]与A[i]
A[i] = A[k];
A[k] = temp;
}

for (int i = 1; i <= n; ++i)
{
printf("%d ",A[i]);
}
printf("\n");
return 0;
}

插入排序(O(m+n))

//直接插入排序
#include<cstdio>
int main(int argc, char const *argv[])
{
int A[6] ={0, 5, 2, 4, 2, 1};
int n = 5;
for (int i = 1; i <= n; ++i)
{
int temp = A[i],j = i;
while(j > 1 && temp < A[j - 1]){
A[j] = A[j - 1];
j--;
}
A[j] = temp;
}

for (int i = 1; i <= n; ++i)
{
printf("%d ",A[i]);
}
printf("\n");
return 0;
}

交换排序(O(n^2))

//冒泡排序
#include<cstdio>
int main(int argc, char const *argv[])
{
int A[10] ={5, 2, 4, 2, 1};
int n = 5;
for (int i = 1; i <= n - 1; ++i)//进行n-1趟
{
for (int j = 0; j < 5 - i; ++j)//第i趟从a[1]到a[n - i - 1]都与下一个数进行比较
{
if(A[j] > A[j + 1]){//如果左边数更大,就交换位置
int temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}

for (int i = 0; i < n; ++i)
{
printf("%d ",A[i]);
}
printf("\n");
return 0;
}