02-选择排序(python、oc)

2017-09-11  本文已影响17人  Young_Blood

简述:从起始位置开始一次往后查找,找到最小的那个元素所处的坐标,然后最小元素与起始位置的元素交换位置。起始位置的坐标+1,继续从起始位置往后查找。。。

python3
def select_sort(alist):
    n = len(alist)
    for i in range(n - 1):
        min_index = i
        for j in range(i + 1,n):
            if alist[min_index] > alist[j]:
                min_index = j
        alist[i], alist[min_index] = alist[min_index], alist[i]


if __name__ == "__main__":
    li = [54,23,12,44,55,88,1]
    print(li)
    select_sort(li)
    print(li)
objective-c
- (void)select_sort:(NSMutableArray *)arr {
    
    for (int i = 0; i < arr.count - 1; i++) { // 比较的次数 [0,count-1) [0,1,2,3]
        int min_index = i;
        for (int j = i; j < arr.count; j++) { // 比较的元素
            if (arr[min_index] > arr[j]) {
                min_index = j;
            }
        }
        NSNumber *temp = arr[i];
        arr[i] = arr[min_index];
        arr[min_index] = temp;
    }
}
上一篇下一篇

猜你喜欢

热点阅读