Python算法在未分类数组中找到最小数字的索引



是否有任何算法可以在python中找到k最小数字的索引?我知道如何使用Numpy模块来实现这一点,但我并不是在寻找。我立即想到的一个方向是必须对算法进行分类。因此,可以说我有一个使用气泡排序在Python中对数组进行排序的算法:

def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
    for j in range(0, n-i-1):
        # Swap if the element found is greater
        # than the next element
        if arr[j] > arr[j+1] :
            arr[j], arr[j+1] = arr[j+1], arr[j]

我不确定如何将此算法修改为,只需返回数组中最小数字的索引。使用排序算法或选择QuickSelect的算法,QuickSort,QuickSort,应表示感谢。<<<<<<<</p>

编辑1:所以说数组是:

a = [12, 11, 0, 35, 16, 17, 23, 21, 5]

然后它必须返回一个数组: index_of_least_k = [2,8,1]

k = 3。

如果我必须修改排序算法说泡泡排序,我会知道如何更改,以便这次交换索引,说:

def modified_bubbleSort(arr, index):
      n = len(arr)
      # Traverse through all array elements
      for i in range(n):
           for j in range(0, n-i-1):
                  # Swap if the element found is greater
                  # than the next element
                  if arr[j] > arr[j+1] :
                         index[j], index[j+1] = index[j+1], index[j]
      return index

array = [12, 11, 0, 35, 16, 17, 23, 21, 5]
index = [0, 1, 2, 3, 4, 5, 6, 7, 8]
indexOfAllsorted = modified_bubblesort(array, index)

在这种情况下,它将返回我:

indexOfAllsorted = [2,8,1,0,4,5,7,6]

我不想要那个值,因为有额外的5个值,为了避免内存在头顶上,我的算法应该只有:

index_of_least_k = [0, 0, 0]

在k = 3的内存中,然后在继续进行时填充它。我希望我明确。

edit2:我不是在寻找在Python中实现这一目标的任何库或模块。

您可以使用heapq.nsmallest从估计的最小项目中获取n。那么,您如何创建一个值得的估计输入值但返回其索引的值?一种方法是使用enumerate函数获取(index, value)对的触觉,然后使用密钥函数仅使用值。

from heapq import nsmallest
from operator import itemgetter
def indices_of_n_smallest(n, seq):
    smallest_with_indices = nsmallest(n, enumerate(seq), key=itemgetter(1))
    return [i for i, x in smallest_with_indices]
array = [12, 11, 0, 35, 16, 17, 23, 21, 5]
indices_of_n_smallest(3, array)
# [2, 8, 1]

这是关于气泡排序的事情。每次内部循环完成迭代时,恰好一个元素都会找到其正确的位置。例如,您的代码每次都会找到最大的元素,因为它正在按顺序排序。让我们将>符号翻转到&lt ;;现在,每次J循环完成时,它都会发现最小的元素。因此,如果您在i = k时停止排序,您将拥有最小的元素。

def modified_bubbleSort(arr, index, k):
  n = len(arr)
  ans = []
  for i in range(k):
       for j in range(0, n-i-1):
              # Swap if the element found is smaller
              # than the next element
              if arr[index[j]] < arr[index[j+1]] :
                     index[j], index[j+1] = index[j+1], index[j]
       ans.append(index[n-i-1])
  return ans

最新更新