Python 精灵排序程序
在本文中,我们将了解如何解决以下问题陈述。
问题陈述 - 我们给定一个数组,我们需要使用精灵排序对其进行排序。
算法
1. Firstly we traverse the array from left to right. 2. Now,if the current element is larger or equal to the previous element then we traverse one step ahead 3. otherwise,if the current element is smaller than the previous element then swap these two elements and traverse one step back. 4. Repeat steps given above till we reach the end of the array
现在,让我们观察下面实现中的解决方案 −
示例
def gnomeSort( arr, n):
index = 0
while index < n:
if index == 0:
index = index + 1
if arr[index] >= arr[index - 1]:
index = index + 1
else:
arr[index], arr[index-1] = arr[index-1], arr[index]
index = index - 1
return arr
# main
arr = [1,4,2,3,6,5,8,7]
n = len(arr)
arr = gnomeSort(arr, n)
print ("Sorted sequence is:")
for i in arr:
print (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