【问题标题】:Can someone explain to me what type of sort this is?有人可以向我解释这是什么类型的吗?
【发布时间】:2019-12-13 11:42:44
【问题描述】:

我找到了这种类型,有人可以向我解释一下它是什么类型的吗?我认为这是一种选择排序是否正确?嵌套循环是如何工作的?

    for (i = 0; i < N; ++i) { 
        for (j = i + 1; j < N; ++j) {
            if (toSort[i] > toSort[j]) {
                temp = toSort[i];
                toSort[i] = toSort[j];
                toSort[j] = temp;

                printf("%d is swapped with %d\n", toSort[i], toSort[j]);  
            }
        }
    }

【问题讨论】:

  • 看起来像冒泡排序。

标签: c arrays loops sorting nested


【解决方案1】:

您发布的算法看起来像冒泡排序,但有一些错误。请参阅下面的伪代码:

procedure bubbleSort(list : array of items)

   loop = list.count;

   for i = 0 to loop-1 do:
      swapped = false

      for j = 0 to loop-1 do:

         if list[j] > list[j+1] then
            swap(list[j], list[j+1]) 
            swapped = true
         end if

      end for

      if not swapped then
         break
      end if

   end for

end procedure return list

这是冒泡排序的优化版本,它使用布尔“标志”来跳过不必要的迭代。

选择排序不同,因为它寻找最小的数字并将其插入到最后的位置。选择排序的伪代码如下:

procedure selection sort 
   list  : array of items
   n     : size of list

   for i = 1 to n - 1
      min = i    

      for j = i+1 to n 
         if list[j] < list[min] then
            min = j;
         end if
      end for

      if indexMin != i  then
         swap(list[min], list[i])
      end if
   end for

end procedure

【讨论】:

    【解决方案2】:

    这看起来像是冒泡排序的一种变体,除了似乎是错误的。在这里,与经典的冒泡排序相比,内部循环看起来做了相反的工作。在经典版本中,内部循环“弹出”当前第 i 个元素,直到它就位。在这个版本中,它试图“下沉”第 i 个元素。但是,请注意,第 j 个元素一直与第 i 个交换,因此只要在我们处于 j 循环时 i 是固定的,我们就会在所有这些元素中做一堆第 j 个元素小于第 i 个。第 i 个用第 j 个修饰,然后第 (j+1) 个元素实际上与第 j 个进行比较。这是错误的(至少这不是经典冒泡排序所做的)。

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      • 2014-12-06
      • 1970-01-01
      • 2019-06-19
      • 2011-08-20
      • 1970-01-01
      相关资源
      最近更新 更多