简体   繁体   English

这算作插入排序吗? 为什么最后会显示一个随机数?

[英]Does this count as an Insertion-Sort? And why does a random number show at the end?

I've been asked to create an insertion sort for an array.我被要求为数组创建插入排序。 My program ended differently from the teacher's, but it sorts the array.我的程序与老师的程序不同,但它对数组进行了排序。 However, I'm curious if it truly counts as a proper insertion sort.但是,我很好奇它是否真的算作正确的插入排序。 Also, at the end of the sorting, some random numbers appear.此外,在排序结束时,会出现一些随机数。 I would appreciate some help with this.我将不胜感激。

#include <iostream>
#define size  6
using namespace std;
void insertion(int v[size]){
    int i,temp;
    for(i=0;i<size;i++){
       while(v[i+1] < v[i]){
            temp = v[i+1];
            v[i+1] = v[i];
            v[i] = temp;
            printArr(v);
            i = 0;
            }
      }
}
int main(){
    int vet[size] = {34,12,15,21,5,88};
    printArr(vet);
    insertion(vet);
    
    return 0;

}

Here is the output, one line at a time:这是 output,一次一行:

34,12,15,21,5,88,
12,34,15,21,5,88,
12,15,34,21,5,88,
12,15,21,34,5,88,
12,15,21,5,34,88,
12,15,5,21,34,88,
12,5,15,21,34,88,
5,12,15,21,34,88,
5,12,15,21,34,44,

Notice the 44 at the end there.注意最后的44。 I don't know why it's there since the code works nicely up until the end.我不知道为什么它在那里,因为代码一直运行良好,直到最后。

Edit: Fixed a damn typo.编辑:修正了一个该死的错字。 My PC turns any lowercase i into uppercase, just forgot to adjust it, but it's not wrong in code.我的电脑将任何小写的 i 变成大写,只是忘记调整它,但代码并没有错。

For starters there is a typo in this statement对于初学者来说,这个声明中有一个错字

v[i+1] = v[I];
         ^^^^ 

It seems you mean看来你的意思

v[i+1] = v[i];
         ^^^^

The while loop while 循环

   while(v[i+1] < v[i]){
        temp = v[i+1];
        v[i+1] = v[I];
        v[i] = temp;
        printArr(v);
        i = 0;
        }

can invoke undefined behavior due to accessing memory beyond the array when i is equal to size - 1 .i等于size - 1时,由于访问数组之外​​的 memory 可以调用未定义的行为。

In any case the approach with the while loop is incorrect and inefficient.在任何情况下,使用 while 循环的方法都是不正确且低效的。 The outer for loop again starts from 0 when a swap of adjacent elements occurred.当相邻元素发生交换时,外部 for 循环再次从 0 开始。

And moreover the function depends on the magic named number 6. That is it is unable to sort arrays of different sizes.而且 function 依赖于名为 6 的魔法。也就是说它无法对不同大小的 arrays 进行排序。

There is a variable mismatch.存在变量不匹配。 Change the capital I to small i.将大写 I 更改为小 i。

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

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