선택 정렬을 위한 Python 프로그램
선택 정렬 알고리즘은 정렬되지 않은 부분에서 최소 요소(오름차순 고려)를 반복해서 찾아 처음에 배치하여 배열을 정렬합니다. 알고리즘은 주어진 배열에서 두 개의 하위 배열을 유지합니다.
선택 정렬을 위한 Python 프로그램
제공된 Python 코드는 선택 정렬 알고리즘을 보여줍니다. 선택 정렬의 시간 복잡도는 O(n^2)입니다. 각 반복에서 코드는 배열의 정렬되지 않은 부분에서 최소 요소의 인덱스를 찾아 현재 인덱스의 요소와 바꿉니다. 이렇게 하면 배열이 왼쪽에서 오른쪽으로 점차 정렬됩니다. 이 예제에서는 배열을 초기화하고 SelectionSort 함수를 적용하여 정렬한 다음 정렬된 배열을 오름차순으로 인쇄합니다. 정렬된 배열은 정렬되지 않은 부분에서 가장 작은 요소를 반복적으로 찾아서 올바른 위치에 배치함으로써 얻어지며 결과적으로 정렬된 배열이 생성됩니다: [-202, -97, -9, -2, 0, 11, 45, 88, 747].
파이썬3
# Selection sort in Python> # time complexity O(n*n)> #sorting by finding min_index> def> selectionSort(array, size):> > > for> ind> in> range> (size):> > min_index> => ind> > for> j> in> range> (ind> +> 1> , size):> > # select the minimum element in every iteration> > if> array[j] min_index = j # swapping the elements to sort the array (array[ind], array[min_index]) = (array[min_index], array[ind]) arr = [-2, 45, 0, 11, -9,88,-97,-202,747] size = len(arr) selectionSort(arr, size) print('The array after sorting in Ascending Order by selection sort is:') print(arr)> |
산출
The array after sorting in Ascending Order by selection sort is: [-202, -97, -9, -2, 0, 11, 45, 88, 747]
시간 복잡도 : 에 2 ).
보조 공간 : O(1).
전체 기사를 참조하세요. 선택 정렬 상세 사항은!