简体   繁体   English

使用堆栈或队列在c ++中实现插入排序?

[英]Implement insertion sort in c++ using Stack or Queue?

Classical insertion sort algorithm with array is 具有数组的经典插入排序算法为

void insertion_sort (int arr[], int length){
        int j, temp;

    for (int i = 0; i < length; i++){
        j = i;

        while (j > 0 && arr[j] < arr[j-1]){
              temp = arr[j];
              arr[j] = arr[j-1];
              arr[j-1] = temp;
              j--;
              }
        }
}

So should it implemented by using stack or queue? 那么应该使用堆栈还是队列来实现?

If you use a vector, you gain the performance that all the memory you're working with is contiguous, but lose performance because you have to copy. 如果使用向量,则可获得的性能是您正在使用的所有内存都是连续的,但由于必须复制而导致性能下降。 If you use a linked list of any type, you gain because you don't have to copy, but you lose because your memory is scattered all over the place. 如果您使用任何类型的链表,您会因为不必复制而获得收益,但由于您的记忆分散在各处而损失了收益。

As such, this will depend on the number of items being sorted, the processor cache, and probably a whole host of other things. 因此,这将取决于要排序的项目数,处理器缓存,以及可能还包括其他所有内容。

Given that this sorting algorithm is known to be slow for any numbers of N, the correct solution is to not worry about performance at all and just use std::sort. 鉴于已知这种排序算法对于N的任何数量都比较慢,因此正确的解决方案是完全不用担心性能,而只需使用std :: sort。

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

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