【发布时间】:2020-11-07 16:53:04
【问题描述】:
一般来说,我正在尝试使用随机生成的数组来获取 C 中排序算法的运行时间。但是,我认为在第一次排序之后,我的函数已经对排序后的数组进行了排序,而不是随机生成的数组。
以下是我的代码示例: 用于我的数组生成和打印
void generator(int A[], int n){
int i;
for(i = 0; i < n+1; i++){
A[i] = rand()%n+1;
}
}
void printer(int A[], int n){
for (int i = 0; i < n; ++i)
{
printf("%d ", A[i]);
}
printf("\n\n");
}
和我的排序:
void bubble(int A[], int n)
int i,j;
for (i = 0; i < n-1; i++ ){
for(j = 0; j < n-i-1; j++){
if(A[j] > A[j+1]){
swap(&A[j], &A[j+1]);
}
}
现在我的主要功能是这样的:
int main(){
int n[] = {5} //this is an example array size, this could be extended
for(int i = 0; i < 1; i++){
int A[n[i]]; //this is were i initialize my array with the size of index i
generator(A[n[i]], n);
for(int j = 0; j < 10; j++){ //run sort 10x
//printer(A, n);
bubble(A,n);
}
}
我使用上面的打印机值来检查数组,但是基于此代码,在第一次运行时,我的排序算法运行随机生成的数组,但是在第 2 到第 10 次运行时,它对已生成的数组进行排序已经。
【问题讨论】:
-
复制数组并对副本进行排序。
-
generator(A[n[i]], n);应该是generator(A, n); -
i < n+1应该是i < n