选择排序
选择排序是一种比较直观的排序算法。它通过不断的在未排序的数组中找出最小(大)的数,然后将它放在已排序数组的末尾,当未排序的数组的个数小于等于1的时候,排序完成。
关键步骤:
1、将需要排序的数组分为两部分,取变量 i 表示已排序数组的坐标。
2、取变量 j = i + 1 表示未排序的数组的起始位置,count 表示数组个数 ,j 到 count 表示未排序的数组,遍历未排序的数组找到最小数的坐标min,将 min 放到已排序数组的末尾,i ++。
3、重复以上步骤,如果 i = count - 1,那么数组排序完毕。
代码实现(Objective-c):
-(void)selectedSort:(NSMutableArray *)mularray {
int count = (int)mularray.count;
for (int i = 0; i < count - 1; i++) {
int min = i;
for (int j = i + 1; j < count; j++) {
if (mularray[min] > mularray[j]) {
min = j;
}
}
[mularray exchangeObjectAtIndex:min withObjectAtIndex:i];
NSLog(@"%@", mularray);
}
}
图片解析:

步骤解析:
1、i = 0,从25,12,22,11中找出最小的数11,将11和已排序数组的末尾(0)交换。
此时数组为:11,25,12,22,64
2、i = 1,从12,22,64中找出最小的数12,将12和已排序数组的末尾(1)交换 。
此时数组为:11,12,25,22,64
3、i = 2,从22,64中找出最小的数22,将22和已排序数组的末尾(2)交换 。
此时数组为:11,12,22,25,64
4、i = 3,将64和已排序数组末尾(3)的数比较,不需要交换 。
5、i = 4,此时i == 5 - 1,排序完成 。
参考资料:
1、GeeksforGeeks
2、维基百科
网友评论