Python 奇偶排序程序
在本文中,我们将学习如何解决以下给定的问题陈述。
问题陈述 − 给定一个数组,我们需要使用奇偶排序对它进行排序。
算法
1. Check if value at index 0 is greater than value at last index,then swap them. 2. sort the initial 2/3rd of the array. 3. sort the last 2/3rd of the array. 4. sort the initial 2/3rd again to confirm.
现在让我们观察下面实现中的解决方案 −
示例
def stoogesort(arr, l, h):
if l >= h:
return
# swap
if arr[l]>arr[h]:
t = arr[l]
arr[l] = arr[h]
arr[h] = t
# more than 2 elements
if h-l+1 > 2:
t = (int)((h-l+1)/3)
# sort first 2/3 elements
stoogesort(arr, l, (h-t))
# sort last 2/3 elements
stoogesort(arr, l+t, (h))
# sort first 2/3 elements again
stoogesort(arr, l, (h-t))
# main
arr = [1,4,2,3,6,5,8,7]
n = len(arr)
stoogesort(arr, 0, n-1)
print ("Sorted sequence is:")
for i in range(0, n):
print(arr[i], end = " ")输出
Sorted sequence is: 1 2 3 4 5 6 7 8

所有变量均在局部范围内声明,并且在上图中可以看到它们的引用。
结论 −
在本文中,我们学习了如何编写 Python 程序进行奇偶排序
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP