简体   繁体   English

有人可以向我解释这是什么类型的吗?

[英]Can someone explain to me what type of sort this is?

I found this sort, can someone explain to me what type of sort it is?我找到了这种类型,有人可以向我解释它是什么类型的吗? Am i right to think this is a selection sort?我认为这是一种选择是否正确? How are the nested loops working?嵌套循环如何工作?

    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]);  
            }
        }
    }

The algorithm you posted looks like bubble sort, but it has a few mistakes.您发布的算法看起来像冒泡排序,但它有一些错误。 See its pseudocode below:请参阅下面的伪代码:

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

This is an optimized version of bubble sort, which uses a boolean "flag" to skip unnecessary iterations.这是冒泡排序的优化版本,它使用布尔“标志”来跳过不必要的迭代。

Selection sort is different as it looks for the smallest number and inserts it in its final place.选择排序是不同的,因为它寻找最小的数字并将其插入到最后的位置。 The pseudocode for selection sort is as follows:选择排序的伪代码如下:

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

This looks like a variation of Bubble sort, with the exception that it seems wrong .这看起来像是冒泡排序的一种变体,但它似乎是错误的 Here, the inner loop looks doing a reverse job compared to the classical Bubble sort.在这里,与经典的冒泡排序相比,内部循环看起来做了相反的工作。 In the classical version, inner loop "pops up" the current i-th element until it is on its place.在经典版本中,内循环“弹出”当前第 i 个元素,直到它就位。 In this version it tries to "sink down" the i-th element.在这个版本中,它试图“下沉”第 i 个元素。 However, note that the the j-th element is swapped with i-th all the time, and so as long as i is fixed while we're in j-loop, we do a mess of j-th elements while all of them are less than i-th.但是,请注意,第 j 个元素始终与第 i 个元素交换,因此只要在 j 循环中时 i 是固定的,我们就会将第 j 个元素弄得一团糟,而所有这些元素小于第 i 个。 The i-th is modified with j-th, and then the (j+1)-th element is in fact compared to j-th.将第 i 个元素修改为第 j 个元素,然后将第 (j+1) 个元素实际上与第 j 个元素进行比较。 This is wrong (at least that is not what the classical Bubble sort does).这是错误的(至少经典冒泡排序不是这样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM