编译器: Xcode
编程语言: c
选择排序的基本思路:
每次从n-I1(I=1、2、3…、n-1 )个记录中选择关键字最小的记录与第I个记录进行交换,作为顺序序列的第I个记录。
例如:
排序对象列: 43、65、4、23、6、98、2、65、7、79
第一批: 2、65、4、23、6、98、43、65、7、79
第二批: 2、4、65、23、6、98、43、65、7、79
第三批: 2、4、6、23、65、98、43、65、7、79
第四批: 2、4、6、7、43、65、98、65、23、79
第五批: 2、4、6、7、23、65、98、65、43、79
第六批: 2、4、6、7、23、43、98、65、65、79
第七批: 2、4、6、7、23、43、65、98、65、79
第八批: 2、4、6、7、23、43、65、65、98、79
第九批: 2、4、6、7、23、43、65、65、79、98
排序的时间复杂度为o(n^2),空间复杂度为o )1)
选择顺序不稳定;
源程序:
# includeiostreamusingnamespacestd; voidselectsort(inta[],int n ) /选择排序(intmix,temp; for(intI=0; 合1; 每次遍历I//数组时,都会找到最小的元素并放在前面,前面的内容被排序{ mix=i; //最小元素下标for(intj=I1; jn; 将j(//上假设的最小要素与数组进行比较,求出最小要素的下标if(a[j]a[mix] ) mix=j; //如果数组中真的有小于假设元素的,交换if(I )!=mix () { temp=a[i]; a[i]=a[mix]; a[mix]=temp; } }}int main () inta [ 10 ]={ 43,65,4,23,6,98,2,65,7,79 }; cout '选择排序:“endl; 选择(a,10; for(intI=0; i10; I ) couta[i] '; coutendl; 返回0; }执行结果:
选择顺序: 2467234365657998 programendedwithexitcode :