[英]Sorting algorithm not correctly sorting
I am following the provided sorting algorithm:我遵循提供的排序算法:
INSERTION-SORT(A)
1 for j <- 2 to length[A]
2 do key <-A[j]
3 Insert A[j] into the sorted sequence A[1..j — 1].
4 i <- j — 1
5 while i > 0 and A[i] > key
6 do A[i + 1] <- A[i]
7 i <- i — 1
8 A[i + 1] <— key
Provided by Introduction to Algorithms by Cormen, I have attempted with the following:由 Cormen 的 Introduction to Algorithms 提供,我尝试了以下内容:
#include <stdlib.h>
#include <stdio.h>
#define MAXSIZE 6
void sorting(int (*A)[MAXSIZE]){
int key;
int i;
size_t size = sizeof(*A)/sizeof((*A)[0]);
for (int j = 1; j < size; j++){
key = (*A)[j];
i = j-1;
do {
(*A)[i+1] = (*A)[i];
i--;
}while(i > 0 && (*A)[i] > key);
(*A)[i+1] = key;
}
for(int k = 0; k < size; k++){
printf("\n%d", (*A)[k]);
}
}
int main(void){
int B[MAXSIZE] = {5, 2, 4, 6, 1, 3};
int result;
sorting(&B);
return 0;
}
However, the output is not sorting correctly.但是,output 排序不正确。 Did I miss something with these steps?
这些步骤我错过了什么吗?
Code is errantly doing a do {} while
when a while {}
is needed.当需要
while {}
时,代码会错误地执行do {} while
。
Consider if the array was initially sorted.考虑数组是否最初排序。 The first
(*A)[i+1] = (*A)[i];
第一个
(*A)[i+1] = (*A)[i];
messes up the array.弄乱数组。
Arrays in C start with index 0 and elements are stored in positions 0 to n-1 Arrays in C 从索引 0 开始,元素存储在位置 0 到 n-1
for (int j = 1; j < size; j++){
You changed "while {}" which check before loop to "{} while", which check after loop, moving element without comparison.您将循环前检查的“while {}”更改为循环后检查的“{} while”,移动元素而不进行比较。
while(i >= 0 && (*A)[i] > key) {
(*A)[i+1] = (*A)[i];
i--;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.