假设我们有一个清单:
a = [4, 8, 1, 7, 3, 0, 5, 2, 6, 9]现在,a.sort()将对列表进行排序。如果我们只想对列表中的一部分进行排序,还在进行呢?在C++中,我们可以写:
int array = { 4, 8, 1, 7, 3, 0, 5, 2, 6, 9 };
int * ptr = array;
std::sort( ptr + 1, ptr + 4 );Python中有类似的方式吗?
发布于 2010-02-16 13:42:31
我会这样写:
a[i:j] = sorted(a[i:j])它也不是就地排序,而是足够快相对较小的部分。
请注意,Python只复制对象引用,因此与实际的就地排序相比,速度损失不会像人们所期望的那么大。
发布于 2010-02-16 18:59:24
如果a是numpy数组,那么要就地对[i, j)范围进行排序,请键入:
a[i:j].sort()示例:
>>> import numpy as np
>>> a = np.array([4, 8, 1, 7, 3, 0, 5, 2, 6, 9])
>>> a[1:4].sort()
>>> a
array([4, 1, 7, 8, 3, 0, 5, 2, 6, 9])发布于 2020-06-16 00:19:18
要在两个索引之间进行排序,我建议使用快速排序。与array[start:end] = sorted(arr[start:end])相比,quicksort的优点是它不需要任何额外的内存,而分配给片需要O(n)额外的内存。
我不相信标准库中有实现,但是自己编写是很容易的。下面是我从https://www.geeksforgeeks.org/quicksort-using-random-pivoting/复制和粘贴的一个实现
import random
def quicksort(arr, start , stop):
if(start < stop):
pivotindex = partitionrand(arr, start, stop)
quicksort(arr , start , pivotindex - 1)
quicksort(arr, pivotindex + 1, stop)
def partitionrand(arr , start, stop):
randpivot = random.randrange(start, stop)
arr[start], arr[randpivot] = arr[randpivot], arr[start]
return partition(arr, start, stop)
def partition(arr,start,stop):
pivot = start # pivot
i = start + 1 # a variable to memorize where the
# partition in the array starts from.
for j in range(start + 1, stop + 1):
if arr[j] <= arr[pivot]:
arr[i] , arr[j] = arr[j] , arr[i]
i = i + 1
arr[pivot] , arr[i - 1] = arr[i - 1] , arr[pivot]
pivot = i - 1
return (pivot) 为了在示例(包括范围)中对索引2和6进行排序,我将执行如下操作:
array = [4, 8, 1, 7, 3, 0, 5, 2, 6, 9]
quicksort(array, 2, 6)
print(array) https://stackoverflow.com/questions/2272819
复制相似问题