gpt4 book ai didi

c++ - 插入数组排序法

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:48:14 24 4
gpt4 key购买 nike

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com