主頁 > 企業開發 > 如何使用插入排序對向量進行排序?

如何使用插入排序對向量進行排序?

2021-10-21 11:59:30 企業開發

我只是在練習使用向量實作選擇排序。但它回傳的向量與我作為輸入給出的向量相同。

此實作適用于陣列,但不適用于向量。

#include<bits/stdc  .h>
using namespace std;
vector<int>  insertionSort(vector<int> v, int n)
{
    for(int i=1;i<=n-1;i  )
    {
        int currentEle = v[i];
        int prevEle = i-1;
        // right index where current is inserted
        while(prevEle>=0 and v[prevEle]>currentEle){
            v[prevEle  1] = v[prevEle];
            prevEle = prevEle-1;

        }
       v[prevEle 1] = currentEle;
    }
      return v;
    
}
int main()
{
    int n;
    cin>>n;
    vector<int> v(n);
    for(int i=0;i<n;i  )
    {
        cin>>v[i];
    }
    insertionSort(v,n);
    for(auto x: v)
    {
        cout<<x<<" ";
        
    }

  //OUTPUTS
    
    Input : 5 3 1 2 4
    Expected Output : 1 2 3 4 5
    My Output : 5 3 1 2 4 

是否有使用相同演算法使用選擇排序對向量進行排序的特定方法?

uj5u.com熱心網友回復:

您沒有將回傳的向量存盤insertionSort到任何內容中。

你可以做:

std::vector<int> result = insertionSort(v,n);

代替:

insertionSort(v,n);

然后列印result而不是v

for (auto &x : result) {
  std::cout << x << " ";
}

其他一些與問題無關但有幫助的要點。

  1. 使用using namespace std被認為是一種不好的做法
  2. 為什么你不應該使用 #include<bits/stdc .h>

uj5u.com熱心網友回復:

我的問題的解決方案是使用向量作為值或參考

vector<int>  insertionSort(vector<int> &v, int n)

在按參考傳遞中,實際引數傳遞給函式。如果按值傳遞引數值復制到另一個變數。所以最好的方法是使用向量作為參考

uj5u.com熱心網友回復:

您正在按值將向量傳遞給insertSort函式,但在函式中,您沒有收集回傳值。最終列印了相同的輸入向量v,因此,您將獲得相同的輸出。

所以你的主要功能應該是這樣的。

int main()
{
    int n;
    cin>>n;
    vector<int> v(n);
    for(int i=0;i<n;i  )
    {
        cin>>v[i];
    }
    auto sortedVector = insertionSort(v,n);
    for(auto x: sortedVector)
    {
        cout<<x<<" ";
        
    }
    return 0;
}

uj5u.com熱心網友回復:

讓我們像除錯器一樣單步除錯您的代碼。在這里,我們將在insertionSort(v,n);即將被呼叫的行上放置一個斷點我們假設用戶已經輸入了有效的未排序輸入整數。我會{3,2,9,5,7}隨意使用在您的情況下無關緊要的向量

我們將按照您的除錯器的方式進入代碼,現在這將因您的特定編譯器和除錯器工具而異,但為了簡單起見,我們可以根據 C 語言的規則概括這里發生的事情。

這里的問題不是在運行時發生的。這里的問題發生在編譯時。它仍然是有效的代碼,因為沒有生成編譯錯誤,因此您認為它一定是運行時錯誤,因為您沒有獲得正確的輸出。

在這里您必須了解 C 編譯器如何解釋函式宣告/定義和函陣列合。編譯時,它會查找您宣告為insertionSort()必須在首次使用前定義的函式在你的情況下是這樣。您在代碼的第 3 行宣告并定義了它。接下來它必須確定它的回傳型別和引數型別是否匹配。

您在第 30 行的呼叫站點: insertionSort(v,n);

在第 3 行找到匹配的宣告/定義:vector<int> insertionSort(vector<int> v, int n);它回傳 a,vector<int>但在 C 中,在函式的呼叫位置可以忽略回傳型別。接下來是引數型別,因為它采用 avector<int>int型別 by value

當您的源代碼被編譯成目標代碼,然后鏈接并翻譯成程式集時。這里發生的事情是,如果您不使用指標或動態記憶體(堆),則此函式將具有自己的堆疊幀,其中這些變數僅可見,并且在此函式的作用域內具有生命周期。

當此函式回傳呼叫站點時,這些變數將被銷毀。此外,按值傳遞通常會導致傳入值的副本。

下面是此函式的堆疊幀可能的樣子: 在這里,我將在措辭演算法圖中使用偽匯編助記符。現在,這是現代硬體的簡化,這是由于編譯器優化和具有多個快取的現代硬體以及可以忽略的向量內在函式,因為它們超出了此處發生的范圍。

  • rsp -> 注冊堆疊指標
  • ret -> 從程序回傳
  • rpt -> 堆疊幀的程序回傳指標
  • r0 -> 零暫存器
  • [r1 - rn] -> 任意多用途暫存器
  • mov -> 操作碼或指令,通過立即值或其他暫存器或記憶體位置將值移動、存盤或加載到某個暫存器中。
 //Stack Frame:
 {   
     // Setup the stack and frame pointers... internal housekeeping

     // Return Type Setup: vector<int>
     rpt assigned to the first value in `vector<int>`
     // this is reserved memory specifically for return values 

     // Parameter Type Setup: vector<int>, int

     // n's initialized value stored in reg1
     mov r1, n's value

     // values to be stored {3,2,9,5,7}
     mov r2, 3
     mov r3, 2
     mov r4, 9
     mov r5, 5
     mov r6, 7

     /* Function Implementation. Not going to convert this to assembly
        However, it will use the rpt pointer to construct the new
        vector that is local to this function after the necessary 
        checks are performed... 

        for(int i=1;i<=n-1;i  )
        {
            int currentEle = v[i];
            int prevEle = i-1;
            // right index where current is inserted
            while(prevEle>=0 and v[prevEle]>currentEle){
                v[prevEle  1] = v[prevEle];
                prevEle = prevEle-1;
            }
            v[prevEle 1] = currentEle;
        }
      */

     // Make sure that shared registers are reassigned or their original values
     // are restored before returning from procedure.
     // More internal housekeeping...

     // Assuming the algorithm is correct and the local registers were assigned
     // to the designated memory pointed to by rpt
     // Then prt would look something like:
     // {rpt[0] = r3, rpt[1] = r2, rpt[2] = r5, rpt[3] = r6, rpt[4] = r1}
     ret rpt
 } 

This is a pseudo example of what your stack frame would look like in assembly sort of. Now, ret is a like a pointer in C/C but in assembly it's a special register that holds a memory address to another register or register segments within the CPU's register files or may even point to cache in modern systems...

Now, within your C code we have reached the end of this function, and it goes out of scope. All local variables are destroyed as that memory is given back to the system and or operating system...

Within the calling of this function you never assign it to any variable from its return value. You passed v into this function by value, and copies are made to the stack. You created a temporary vector internal to this function and performed the sorting algorithm. You return from this function and never use its return value.

In your next line section of C code You are using a ranged based for loop and traversing through main's variable v which was assigned the values {3,2,9,5,7} from the user input.

You passed this into your function by value which is copied information into temporaries. And main's v variable which lives within its own stack frame is never modified. The temporary return variable within insertionSort()' stack frame is the one that was changed.

This isn't a compile time nor a runtime error. This is just a bad implementation design of your algorithm by not fully understanding the specifications of the language and how the compiler treats it.

To fix this function you can drop the return type and pass by reference. The signature will look like this:

void insertionSort(vector<int>& v, int n);

Here a reference to the variable is passed into the function. This time around when your compile sees this and generates the object code later to be translated into assembly. It doesn't make a copy of these values, it uses the same registers or cache lines directly.

In this case, the object being passed into this function can be modified after any computations have been performed on it.

Here's a simple example of a basic integer add function replicating exactly what you have done:

// Pass By Value:
int add(int a, int b) {
    a = a b;
    return a;
}

int main() {
    int a = 3;
    int b = 5;
    add(a, b);
    std::cout << a;
    return 0;
} 

Here you're expecting to see 8 printed, but in fact a from main is never modified and 3 will be printed to your console and you never used the return value from the function.

Let's check the pass by reference version:

void add(int& a, int b) {
    a = a b;
    return a;
}

int main() {
    int a = 3;
    int b = 5;
    add(a, b);
    std::cout << a;
    return 0;
}

In this version because a reference to main's a is used directly within the stack frame of add() main's a will be modified. This time when you print to the console you will see an 8.

I hope this helps to clear up the different ways of passing parameter types into functions within C . You can pass by value, by reference and by pointer and some of them have const versions which is a out of the scope of this topic. Also, do not rely on your parameter or function argument ordering when implementing your algorithms. There is no specification or single use convention or guarantee in how a specific compiler will set up a function's arguments or parameter list when generating the necessary assembly. There are various calling conventions and you would have to know which compiler you are using and what calling convention is being used.

I hope this helps you to understand what is happening with your code, what's going on under the hood at different levels of abstraction and why you are getting the results that you are getting and to help you understand what type of error this is.

Everyone else seems to just say, "passing by value and not reference" assuming you know what they are and mean... I'm treating you as if this was your first day at looking at code or a new language.

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/328472.html

標籤:C 向量 C 17

上一篇:為什么這個用于C 集合的自定義比較器的行為是這樣的?

下一篇:在C 中使用Liebniz公式逼近Pi

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • IEEE1588PTP在數字化變電站時鐘同步方面的應用

    IEEE1588ptp在數字化變電站時鐘同步方面的應用 京準電子科技官微——ahjzsz 一、電力系統時間同步基本概況 隨著對IEC 61850標準研究的不斷深入,國內外學者提出基于IEC61850通信標準體系建設數字化變電站的發展思路。數字化變電站與常規變電站的顯著區別在于程序層傳統的電流/電壓互 ......

    uj5u.com 2020-09-10 03:51:52 more
  • HTTP request smuggling CL.TE

    CL.TE 簡介 前端通過Content-Length處理請求,通過反向代理或者負載均衡將請求轉發到后端,后端Transfer-Encoding優先級較高,以TE處理請求造成安全問題。 檢測 發送如下資料包 POST / HTTP/1.1 Host: ac391f7e1e9af821806e890 ......

    uj5u.com 2020-09-10 03:52:11 more
  • 網路滲透資料大全單——漏洞庫篇

    網路滲透資料大全單——漏洞庫篇漏洞庫 NVD ——美國國家漏洞庫 →http://nvd.nist.gov/。 CERT ——美國國家應急回應中心 →https://www.us-cert.gov/ OSVDB ——開源漏洞庫 →http://osvdb.org Bugtraq ——賽門鐵克 →ht ......

    uj5u.com 2020-09-10 03:52:15 more
  • 京準講述NTP時鐘服務器應用及原理

    京準講述NTP時鐘服務器應用及原理京準講述NTP時鐘服務器應用及原理 安徽京準電子科技官微——ahjzsz 北斗授時原理 授時是指接識訓通過某種方式獲得本地時間與北斗標準時間的鐘差,然后調整本地時鐘使時差控制在一定的精度范圍內。 衛星導航系統通常由三部分組成:導航授時衛星、地面檢測校正維護系統和用戶 ......

    uj5u.com 2020-09-10 03:52:25 more
  • 利用北斗衛星系統設計NTP網路時間服務器

    利用北斗衛星系統設計NTP網路時間服務器 利用北斗衛星系統設計NTP網路時間服務器 安徽京準電子科技官微——ahjzsz 概述 NTP網路時間服務器是一款支持NTP和SNTP網路時間同步協議,高精度、大容量、高品質的高科技時鐘產品。 NTP網路時間服務器設備采用冗余架構設計,高精度時鐘直接來源于北斗 ......

    uj5u.com 2020-09-10 03:52:35 more
  • 詳細解讀電力系統各種對時方式

    詳細解讀電力系統各種對時方式 詳細解讀電力系統各種對時方式 安徽京準電子科技官微——ahjzsz,更多資料請添加VX 衛星同步時鐘是我京準公司開發研制的應用衛星授時時技術的標準時間顯示和發送的裝置,該裝置以M國全球定位系統(GLOBAL POSITIONING SYSTEM,縮寫為GPS)或者我國北 ......

    uj5u.com 2020-09-10 03:52:45 more
  • 如何保證外包團隊接入企業內網安全

    不管企業規模的大小,只要企業想省錢,那么企業的某些服務就一定會采用外包的形式,然而看似美好又經濟的策略,其實也有不好的一面。下面我通過安全的角度來聊聊使用外包團的安全隱患問題。 先看看什么服務會使用外包的,最常見的就是話務/客服這種需要大量重復性、無技術性的服務,或者是一些銷售外包、特殊的職能外包等 ......

    uj5u.com 2020-09-10 03:52:57 more
  • PHP漏洞之【整型數字型SQL注入】

    0x01 什么是SQL注入 SQL是一種注入攻擊,通過前端帶入后端資料庫進行惡意的SQL陳述句查詢。 0x02 SQL整型注入原理 SQL注入一般發生在動態網站URL地址里,當然也會發生在其它地發,如登錄框等等也會存在注入,只要是和資料庫打交道的地方都有可能存在。 如這里http://192.168. ......

    uj5u.com 2020-09-10 03:55:40 more
  • [GXYCTF2019]禁止套娃

    git泄露獲取原始碼 使用GET傳參,引數為exp 經過三層過濾執行 第一層過濾偽協議,第二層過濾帶引數的函式,第三層過濾一些函式 preg_replace('/[a-z,_]+\((?R)?\)/', NULL, $_GET['exp'] (?R)參考當前正則運算式,相當于匹配函式里的引數 因此傳遞 ......

    uj5u.com 2020-09-10 03:56:07 more
  • 等保2.0實施流程

    流程 結論 ......

    uj5u.com 2020-09-10 03:56:16 more
最新发布
  • 使用Django Rest framework搭建Blog

    在前面的Blog例子中我們使用的是GraphQL, 雖然GraphQL的使用處于上升趨勢,但是Rest API還是使用的更廣泛一些. 所以還是決定回到傳統的rest api framework上來, Django rest framework的官網上給了一個很好用的QuickStart, 我參考Qu ......

    uj5u.com 2023-04-20 08:17:54 more
  • 記錄-new Date() 我忍你很久了!

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 大家平時在開發的時候有沒被new Date()折磨過?就是它的諸多怪異的設定讓你每每用的時候,都可能不小心踩坑。造成程式意外出錯,卻一下子找不到問題出處,那叫一個煩透了…… 下面,我就列舉它的“四宗罪”及應用思考 可惡的四宗罪 1. Sa ......

    uj5u.com 2023-04-20 08:17:47 more
  • 使用Vue.js實作文字跑馬燈效果

    實作文字跑馬燈效果,首先用到 substring()截取 和 setInterval計時器 clearInterval()清除計時器 效果如下: 實作代碼如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta ......

    uj5u.com 2023-04-20 08:12:31 more
  • JavaScript 運算子

    JavaScript 運算子/運算子 在 JavaScript 中,有一些運算子可以使代碼更簡潔、易讀和高效。以下是一些常見的運算子: 1、可選鏈運算子(optional chaining operator) ?.是可選鏈運算子(optional chaining operator)。?. 可選鏈操 ......

    uj5u.com 2023-04-20 08:02:25 more
  • CSS—相對單位rem

    一、概述 rem是一個相對長度單位,它的單位長度取決于根標簽html的字體尺寸。rem即root em的意思,中文翻譯為根em。瀏覽器的文本尺寸一般默認為16px,即默認情況下: 1rem = 16px rem布局原理:根據CSS媒體查詢功能,更改根標簽的字體尺寸,實作rem單位隨螢屏尺寸的變化,如 ......

    uj5u.com 2023-04-20 08:02:21 more
  • 我的第一個NPM包:panghu-planebattle-esm(胖虎飛機大戰)使用說明

    好家伙,我的包終于開發完啦 歡迎使用胖虎的飛機大戰包!! 為你的主頁添加色彩 這是一個有趣的網頁小游戲包,使用canvas和js開發 使用ES6模塊化開發 效果圖如下: (覺得圖片太sb的可以自己改) 代碼已開源!! Git: https://gitee.com/tang-and-han-dynas ......

    uj5u.com 2023-04-20 08:01:50 more
  • 如何在 vue3 中使用 jsx/tsx?

    我們都知道,通常情況下我們使用 vue 大多都是用的 SFC(Signle File Component)單檔案組件模式,即一個組件就是一個檔案,但其實 Vue 也是支持使用 JSX 來撰寫組件的。這里不討論 SFC 和 JSX 的好壞,這個仁者見仁智者見智。本篇文章旨在帶領大家快速了解和使用 Vu ......

    uj5u.com 2023-04-20 08:01:37 more
  • 【Vue2.x原始碼系列06】計算屬性computed原理

    本章目標:計算屬性是如何實作的?計算屬性快取原理以及洋蔥模型的應用?在初始化Vue實體時,我們會給每個計算屬性都創建一個對應watcher,我們稱之為計算屬性watcher ......

    uj5u.com 2023-04-20 08:01:31 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:01:10 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:00:32 more