排序之选择排序

它的基本思想是:首先在未排序的数列中找到最小(or最大)元素,然后将其存放到数列的起始位置;接着,再从剩余未排序的元素中继续寻找最小(or最大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。选择排序代码如下:
#include < stdio.h >

void exchange(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

void selectionsort(int *array,int max)
{
int i,j;
for(i=0;i< max-1; i++)
{
int smallest =i;
for(j=i+1;j < max;j++)
{
if(array[j] < array[smallest])
{
smallest = j;
}
}
exchange(&array[i],&array[smallest]);
}
}



int main()
{
int i;
int array[]={5,2,3,4,5,6,7,1,9};
int length=sizeof(array)/sizeof(array[0]);
printf("处理之前:\n");
for(i=0;i < length;i++)
{
printf("%d",array[i]);
}
printf("\n排序之后\n");
selectionsort(array,length);
for(i=0;i < length;i++)
{
printf("%d",array[i]);
}
return 0;
}
时间复杂度:
最好O(n2);
最坏O(n2);
稳定性:不稳定
posted @ 2014-04-01 10:41  dreamsyeah  阅读(102)  评论(0编辑  收藏  举报