#include <stdio.h> #define MAXSIZE 9 /* 用于要排序数组个数最大值,可根据需要修改 */ typedef struct { int r[MAXSIZE]; int length; /* 用于记录顺序表的长度 */ }SqList; /* 交换L中数组r的下标为i和j的值 */ void swap(SqList * L, int i, int j){ int temp=L->r[i]; L->r[i]=L->r[j]; L->r[j]=temp; } //打印L中数组的值 void print(SqList L){ int i; for(i=0; i < L.length; i++) printf("%3d",L.r[i]); printf(" "); } //简单选择排序 void selectsort(SqList * L){ int i,j,min; for(i=0; i<L->length; i++){ min=i;//设min为最小值的下标 for(j=i+1; j<L->length; j++){ if(L->r[j]<L->r[min]){ min=j; } } if(min!=i) swap(L,min,i);//下标min和i的内容交换 } } int main(){ SqList L; int num[10] ={5,3,2,4,6,1,7,8,9}; for(int i=0; i<9; i++){ L.r[i]=num[i]; }//注意给数组赋值的方法 L.length=9; //简单选择排序 selectsort(&L); print(L); return 0; }
比较次数依然是n(n-1)/2,但交换次数最差的时候是(n-1);
时间复杂度O(n^2)