C ++向量插入排序算法方法 - 传递向量到方法中 [英] C++ vector insertion sort algorithm method - pass vector into method

查看:384
本文介绍了C ++向量插入排序算法方法 - 传递向量到方法中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ive看起来无处不在,无论什么算法,我发现(如果任何lol)插入排序在c ++的向量,它不工作,所以im假设它与我的代码有关。任何人都可以帮助我找到一种方式,我可以传递一个方法作为参数的向量,然后做一个插入排序呢?此时,它会等待几秒钟,并显示所有未排序的值:(

Ive look everywhere and whatever algorithm I find (if any lol) for insertion sort on a vector in c++, it wont work so im assuming it has something to do with my code. Can anyone help me find a way I can pass a vector into a method as an argument and then do an insertion sort on it? At the moment it waits for a few seconds and shows all the values unsorted :(

插入排序代码

void insertionSort (vector<int> data, int n) 
{
int i, j, tmp;

 for (i=1; i<n; i++)
 {
     j=i;
     tmp=data[i];
     while (j>0 && tmp<data[j-1])
     {
           data[j]=data[j-1];
           j--;
     }
     data[j]=tmp;
 }

代码的重要部分

        cout << "insertion sort" << endl;
        system("pause");
        insertionSort(numberVectors, i);

让我知道如果你不认为这个代码有什么不好,你想让我更多地向你展示,

let me know if you dont think theres anything wrong with that code and you want me to show you more, should just be this bit though, the other stuff is irrelavent i think

推荐答案

您的函数按值接受其参数;这意味着它会获得一个复制

Your function accepts its argument by value; this means it gets a copy. You sort the copy, in vain.

将其更改为引用:

void insertionSort (vector<int>& data, int n) 

这篇关于C ++向量插入排序算法方法 - 传递向量到方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆