python选择排序_Python选择排序

本文介绍了Python选择排序算法的工作原理,包括其升序排序的过程和算法步骤。选择排序的时间复杂度在所有情况下均为O(n^2),因此不适合处理大规模数据。文章还提供了Python代码实现选择排序的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 Selection Sort 1

Step 2:

第2步:

Python Selection Sort 2

Step 3:

第三步:

Python Selection Sort 3

Step 4:

第4步:

Python Selection Sort 4

Step 5:

步骤5:

Python Selection Sort 5

Step 6:

步骤6:

Python Selection Sort 6

算法 (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中选择排序的实现。

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选择排序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值