【问题标题】:How to retain the unsorted Array in C after sorting排序后如何在C中保留未排序的数组
【发布时间】: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 &lt; n+1 应该是i &lt; n

标签: arrays c sorting


【解决方案1】:

复制数组并对其进行排序。

此外,所有其他函数的 n 参数应为 n[i]

int main(void){
    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[i]);
        for(int j = 0; j < 10; j++){ //run sort 10x
            int A_copy[n[i]];
            memcpy(A_copy, A, sizeof(A));
            bubble(A_copy, n[i]);
            printer(A_copy, n[i])
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 2022-01-10
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 2012-08-09
    相关资源
    最近更新 更多