选择排序
工作原理:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
插入排序
工作原理:是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
C语言实现:#include<stdio.h>
void selection_sort(int a[], int n)
{
int i, j,temp;
for (i = 0; i < n - 1; i++)
{
int min = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min])
min = j;
temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}
void insertion_sort(int a[], int n) {
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
for (j = i; j > 0 && a[j - 1] > temp; j--) {
a[j] = a[j - 1];
}
a[j] = temp;
}
}
int main() {
int a[] = { 4,8,1,2,0,2,5,6,9,7 };
//selection_sort(a, 10);
insertion_sort(a, 10);
return 0;
}
#include<stdio.h>
void selection_sort(int a[], int n)
{
int i, j,temp;
for (i = 0; i < n - 1; i++)
{
int min = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min])
min = j;
temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}
void insertion_sort(int a[], int n) {
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
for (j = i; j > 0 && a[j - 1] > temp; j--) {
a[j] = a[j - 1];
}
a[j] = temp;
}
}
int main() {
int a[] = { 4,8,1,2,0,2,5,6,9,7 };
//selection_sort(a, 10);
insertion_sort(a, 10);
return 0;
}