学习之后,自己练习手写一下排序算法,加深印象
原理:通过n-i次关键词的比较,从n-i+1个记录中选出关键词最小的记录,并和第i(1<=i<=n)个记录交换之。与冒泡排序相比,其交换的次数减少了许多。
#define MAXSIZE 10
#include <stdio.h>
struct a{
int array[MAXSIZE]; //数组用于存储排序数据
int length; //用于存储数组长度信息,
};
void init_array(struct a *L){ //初始化数组
int i;
L->length = MAXSIZE;
for (i=1;i<L->length;i++){ //索引为0的项留作备用
scanf("%d",&(L->array[i]));
}
}
void swap(struct a *L,int i,int j){ //交换数组项
int temp = L->array[i];
L->array[i] = L->array[j];
L->array[j] = temp;
}
void print(struct a *L){ //打印数组项
int i;
for (i=1;i<L->length;i++){
printf("%d ",L->array[i]);
}
}
void selectSort(struct a *L){ //排序算法
int i,j,min;
for (i=1;i<L->length;i++){
min = i;
for (j=i+1;j<L->length;j++){
if (L->array[min]>L->array[j]){
min = j;
}
}
if (i!=min){
swap(L,i,min);
}
}
}
int main(){
struct a List;
init_array(&List);
printf("排序前:");
print(&List);
selectSort(&List);
printf("\n排序后:");
print(&List);
return 0;
}
算法时间复杂度:O(n2)