排序
插入排序
#include<iostream>
using namespace std;
void insert_sort(int a[]){
for (int j = 2 ; j < 10 ; j ++){
int key = a[j];
int i = j - 1;
while (i > 0 && a[i] > key){
a[i + 1] = a[i];
i--;
}
a[i + 1] = key;
}
}
int main(){
int a[10] = {0,3,4,1,5,7,8,9,2,6};
insert_sort(a);
for (int i = 0 ; i < 10 ; i ++){
printf("%d ",a[i]);
}
return 0;
}
选择排序
void select_sort(int a[]){
for (int i = 1 ; i < 10 ; i ++){
int m = i;
for (int j = i+1 ; j < 10 ; j ++){
if (a[m] > a[j]) m = j;
}
if (m != i) swap(a[m],a[i]);
}
}
int main(){
int a[10] = {0,3,4,1,5,7,8,9,2,6};
select_sort(a);
for (int i = 0 ; i < 10 - 1 ; i ++){
printf("%d",a[i]);
}
return 0;
}
冒泡排序
void bubble_sort(int a[]){
for (int i = 1 ; i < 10 - 1; i ++){
for (int j = 1; j < 10 - i ; j ++){
if (a[j+1] < a[j]) swap(a[j+1],a[j]);
}
}
}
int main(){
int a[10] = {0,3,4,1,5,7,8,9,2,6};
bubble_sort(a);
for (int i = 0 ; i < 10 ; i ++){
printf("%d",a[i]);
}
return 0;
}
评论区