【问题标题】:Insertion Array Sorting Method插入数组排序方法
【发布时间】:2015-12-08 01:43:28
【问题描述】:

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

//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;
}

【问题讨论】:

  • 尝试将您的第一个 for 循环更改为从 int i=1 开始... en.wikipedia.org/wiki/Insertion_sort
  • 它仍然产生相同的排序。我想我在做类似于 wiki 页面的事情。
  • 是的,与*链接相比,您的算法看起来是正确的(除此之外)。可能就是您打印排序数组的方式吗?也许也发布该代码。
  • @NicholasHayden 不要对这么多数字进行排序,而是尝试使用 3、4 或 5 个数字的代码。如果您无法对一个小列表进行排序,那么您将自己淹没在试图找出 100 个数字的问题所在是没有意义的。
  • 另外,如果 INTSIZE 是你的数组的大小,你应该写 for(int i = 0; i &lt; INITSIZE; i++) 而不是 INITSIZE - 1,否则你的最后一个元素将不会被排序。除此之外,你提供的代码对我有用,所以它一定是别的东西。

标签: c++ sorting insertion-sort


【解决方案1】:

这个问题的解决方案是通过@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;   

    }
}

【讨论】: