python选择排序_Python选择排序

python选择排序

Here you’ll learn about python selection sort algorithm with program example.

在这里,您将通过程序示例了解python选择排序算法。

Selection sort is one of the easiest sorting algorithm out there. In Selection sort, to sort an unsorted array, all we have to do is find the minimum in the array and swap it with the first element in the unsorted array. After each swapping increase the starting index of the array by one.

选择排序是最简单的排序算法之一。 在选择排序中,要对未排序的数组进行排序,我们要做的就是在数组中找到最小值,然后将其与未排序的数组中的第一个元素交换。 每次交换之后,将数组的起始索引增加一个。

This is for sorting in ascending order. If we want to sort it into descending order find the maximum instead of minimum and replace with the first element in unsorted array.

这是按升序排序的。 如果要按降序排序,请找到最大值而不是最小值,并替换为未排序数组中的第一个元素。

Python选择排序 (Python Selection Sort)

(Example)

We have an unsorted array-

我们有一个未排序的数组-

[4,8,19,2,28,21]

[4,8,19,2,28,21]

Step 1:

第1步:

python选择排序_Python选择排序

Step 2:

第2步:

python选择排序_Python选择排序

Step 3:

第三步:

python选择排序_Python选择排序

Step 4:

第4步:

python选择排序_Python选择排序

Step 5:

步骤5:

python选择排序_Python选择排序

Step 6:

步骤6:

python选择排序_Python选择排序

算法 (Algorithm)

If we have an array of n elements.

如果我们有n个元素的数组。

Step 1:- set MIN = 0

步骤1:-设定MIN = 0

Step 2:- find minimum element in array

步骤2:-在数组中找到最小元素

If exists then swap with element at MIN

如果存在,则与MIN处的元素交换

Step 3:- increase MIN by 1

步骤3:-将MIN加1

Step 4:- go to Step 2 until  array is sorted (for n-1 times)

步骤4:-转到步骤2直到对数组排序(n-1次)

时间复杂度 (Time Complexity)

  • Best Case = O(n)2

    最佳情况= O(n) 2

  • Average Case = O(n)2

    平均情况= O(n) 2

  • Worst Case = O(n)2

    最坏情况= O(n) 2

Note: for larger arrays we never use selection sort.

注意:对于更大的数组,我们从不使用选择排序。

Python选择排序程序 (Python Selection Sort Program)

Below is the implementation of selection sort in python.

以下是python中选择排序的实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
arr =[4,8,19,2,28,21]
min = 0    #set min = 0
n = len(arr)
while(min <= n-1):
  s_i = min
  while(s_i <= n-1):      #finding minimum
    if (arr[s_i] < arr[min]):
      arr[min],arr[s_i] = arr[s_i],arr[min]   #swapping element at start index with minimum
    s_i = s_i+1
  min = min+1
for element in arr:
   print element
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
arr = [ 4 , 8 , 19 , 2 , 28 , 21 ]
min = 0      #set min = 0
n = len ( arr )
while ( min <= n - 1 ) :
   s_i = min
   while ( s_i <= n - 1 ) :        #finding minimum
     if ( arr [ s_i ] < arr [ min ] ) :
       arr [ min ] , arr [ s_i ] = arr [ s_i ] , arr [ min ]    #swapping element at start index with minimum
     s_i = s_i + 1
   min = min + 1
for element in arr :
   print element

Output

输出量

2 4 8 19 21 28

2 4 8 19 21 28

Comment below if you have any queries related to above python selection sort tutorial.

如果您对上面的python选择排序教程有任何疑问,请在下面评论。

翻译自: https://www.thecrazyprogrammer.com/2017/11/python-selection-sort.html

python选择排序