插入阵列排序方法

Insertion Array Sorting Method

本文关键字:方法 排序 阵列 插入      更新时间:2023-10-16

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

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