C++ 插入数组排序法
我目前是一名研究插入排序方法的学生。 代码如下:C++ 插入数组排序法,c++,sorting,insertion-sort,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];
//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
我在错误地编码什么
谢谢
编辑:
//在主。。。
打印(插入排序值,“插入排序数组”);
//打印功能
无效打印(整数VAL[],字符串s){
这个问题的解决办法是通过@PaulMcKenzie解决的。
该行:
for(int i = 0; i < INITSIZE - 1; i++){
for(int i=0;i
需要成为:
for(int i = 0; i <= INITSIZE - 1; i++){
for(int i=0;i temp;k--){
插入值[k]=插入值[k-1];
}
//将选中的值插入回数组中
插入值[k]=温度;
}
}
尝试将的第一个循环更改为从int i=1开始。。。它仍然生产同样的产品。我想我做的事情和维基百科页面类似。是的,与维基百科链接相比,你的算法看起来是正确的(除此之外)。这可能是打印排序数组的方式吗?也可以发布该代码。@NicholasHayden不要对这么多数字进行排序,而是用3、4或5个数字来尝试代码。如果你不能对一个小列表进行排序,那么你就没有必要试图找出100个数字的错误所在。另外,如果INTSIZE是数组的大小,你应该为(int i=0;i,而不是INITSIZE-1
,否则你的最后一个元素就不会被排序。除此之外,您提供的代码适用于我,因此它一定是其他代码。
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;
}
}