02-ソートの選択(python、oc)
1048 ワード
簡単に説明します.開始位置から1回後に検索し、最小の要素が位置する座標を見つけ、最小要素と開始位置の要素が位置を交換します.開始位置の座標+1、開始位置から後へ検索を続けます..最適時間複雑度O(n²) 最悪時間複雑度O(n²) 安定性:不安定(昇順毎に最大を選択する場合を考慮) python3
objective-c
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;
}
}