美文网首页
02-选择排序(python、oc)

02-选择排序(python、oc)

作者: Young_Blood | 来源:发表于2017-09-11 10:10 被阅读17次

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

    • 最优时间复杂度 O(n²)
    • 最坏时间复杂度 O(n²)
    • 稳定性:不稳定(考虑升序每次选择最大的情况)
    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:02-选择排序(python、oc)

          本文链接:https://www.haomeiwen.com/subject/nhvxsxtx.html