c++ - 插入数组排序法

标签 c++ sorting insertion-sort

我目前是一名研究插入排序方法的学生。 下面是代码:

//Insertion Sorting of an Integer array
void InsertionSort(int insertVals[]){


    //Systematic processing of the Array
    for(int i = 0; i < INITSIZE - 1; i++){
        //Value to check
        int temp = insertVals[i];

        //Index placeholder for the insterion sort
        int k;

        //Shifts the int array
        for(k = i; k > 0 && insertVals[k-1] > temp; k--){
            insertVals[k] = insertVals[k-1];
        }

        //Inserts the checked value back into the array
        insertVals[k] = temp;   

    }
}

在我的测试中,我给了它从左到右的数组:

307 249  73 158 430 272  44 378 423 209 
440 165 492  42 487   3 327 229 340 112 
303 169 209 157  60 433  99 278 316 335 
 97 326  12 267 310 133 479 149  79 321 
467 172 393 336 485 245 228  91 194 357 
  1 153 208 444 168 490 124 196  30 403 
222 166  49  24 301 353 477 408 228 433 
298 481 135  13 365 314  63  36 425 169 
115  94 129   1  17 195 105 404 451 298 
188 123   5 382 252  66 216 337 438 144

该方法从左到右产生:

314  63 314  63  36 425  36 169 425 169 
115 115  94 129  94 129   1  17 195 105 
404 451 298 188 123   5 382 252  66 216 
337 438 144   1  17 195 105 404 451 298 
188 123   5 382 252  66 216 337 438 144 
228 229 245 249 252 267 272 278 298 298 
301 303 307 310 314 316 321 326 327 335 
336 337 340 353 357 365 378 382 393 403 
404 408 423 425 430 433 433 438 440 444 
451 467 477 479 481 485 487 490 492 144

我在什么地方编码不正确?

谢谢!

编辑:

//In main...
Printing(insertionSortValues, "Insertion Sorted Array");

//Function for Print
void Printing(int vals[], string s){
    cout << s << ":" << endl;
    for(int i = 0; i < INITSIZE; i++){
        if(i % 10 == 0){
            cout << endl;
        }
        cout << setw(3) << vals[i] << " ";
    }
    cout << endl;
}

最佳答案

这个问题的解决方案是通过@PaulMcKenzie 解决的。 线路:

for(int i = 0; i < INITSIZE - 1; i++){

需要成为:

for(int i = 0; i <= INITSIZE - 1; i++){

下面是修正后的函数。

//Insertion Sorting of an Integer array
void InsertionSort(int insertVals[]){


    //Systematic processing of the Array
    for(int i = 0; i <= INITSIZE - 1; i++){
        //Value to check
        int temp = insertVals[i];

        //Index placeholder for the insterion sort
        int k;

        //Shifts the int array
        for(k = i; k > 0 && insertVals[k-1] > temp; k--){
            insertVals[k] = insertVals[k-1];
        }

        //Inserts the checked value back into the array
        insertVals[k] = temp;   

    }
}

关于c++ - 插入数组排序法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34146583/

相关文章:

algorithm - 线性排序下如何考虑桶排序?

scala - 插入排序在我用 Scala 编写的代码中不起作用

c++ - 使用列表对象内部对象的派生函数

javascript - 为什么这个洗牌算法没有偏差

c++ - 编译时使用自省(introspection)

java - 存储多个相关值进行排序的最有效方法?

c - 插入排序函数不会列出排序后的所有元素

c - 如何将插入排序转换为 O(n logn) 算法?

c++ - 如何生成唯一的文件名或路径?

c++ - 读取 .vtk 文件