有人可以告诉我这是什么类型的吗?

时间:2019-12-13 11:42:44

标签: c arrays loops sorting nested

我找到了这种排序方式,有人可以向我解释这种排序方式是哪种类型?我认为这是一种选择类型吗?嵌套循环如何工作?

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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

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