以从小到大排序为例,选择排序使得循环过程中,每次循环后最小值在到最前面,冒泡排序通过不断两两比较,使得最小值向前浮现。可以用C语言写两种排序的简单代码。
选择排序
#include <stdio.h>
#define N 6
int main(){
int i = 0, j = 0, temp = 0, t = 0;
int a[N] = {4,8,0,2,1,5};
for (i = 0; i < N - 1; i++){
t = i;
for (j = i + 1; j < N; j++){
if (a[t] > a[j]){
temp = a[t];
a[t] = a[j];
a[j] = temp;
}
}
}
for (i = 0; i < N; i++){
printf("%d ",a[i]);
}
return 0;
}
冒泡排序
#include <stdio.h>
#define N 6
int main(){
int i = 0, j = 0, temp = 0;
int a[N] = {4,8,0,2,1,5};
for (i = 0; i < N; i++){
for (j = 0; j < N -1 - i;j++){
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
for (i = 0; i < N; i++){
printf("%d ",a[i]);
}
return 0;
}