c - 插入排序 - C 中比较和交换的计数

标签 c count comparison swap insertion-sort

如何计算插入排序中的比较和交换次数?我有一个包含 10 个随机数的数组。如果有人帮助我如何在这个程序中放入 20、50、100、200、500、1000、2000 和 5000 个随机数,我将非常高兴。这个问题我想了很久,还是没有找到解决办法。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>            
int main()
{

    int array[10];
    int i, j, n, temp;
    n = 10;
    for (i = 0; i < n; i++)
        array[i] = rand();

    /*Sort*/
    for (i = 1; i < n; i++) {
        j = i;
        while ((j > 0) && (array[j - 1] > array[j])) {
            temp = array[j - 1];
            array[j - 1] = array[j];
            array[j] = temp;
            j--;
        }
    }
    /* Print */
    printf("Sorted Array\n");
    for (i = 0; i < n; i++)
        printf("%d \n", array[i]);
    return 0;
}

最佳答案

这是一段代码,您可以使用它来找出插入排序中比较和交换的总数

   #include <stdio.h>
   #include <stdlib.h>
   #include <time.h>            

   int main()
   {

      int array[10];
      int i, j, n, temp,no_swap=0,comp=0;//variables to find out swaps and comparisons 
      n = 10;
      for (i = 0; i < n; i++)
      array[i] = rand(10);

/*Sort*/
      for (i = 1; i < n; i++) {
      j = i;
      comp++;
      while ((j > 0) && (array[j - 1] > array[j])) {
            if(array[j-1]>array[j]){
            comp++;
        }
        temp = array[j - 1];
        array[j - 1] = array[j];
        array[j] = temp;
        j--;

        no_swap++;//increment swap variable when actually swap is done
    }
}
/* Print */

      printf("\nNo of swaps = %d",no_swap);
      printf("\nNo of comparisions  = %d",comp);
      printf("\nSorted Array\n");
      for (i = 0; i < n; i++)
          printf("%d \n", array[i]);
      return 0;
 } 

关于c - 插入排序 - C 中比较和交换的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34274725/

相关文章:

c - 使用文件描述符打开读取文件

python - 用python计算数据字符串中的nan

python - 在python中为任何对象创建无穷大和负无穷大

Python "in"比较不同字长的字符串

c - 如何在c中正确使用realloc?

c - 哪些项目(结构)知道它们在数组中的位置的静态数组

c - 是否可以使用 autoconf 检查 nvcc 编译?

php - count 子句输出数据库中的所有记录 - mysql

R 项目组合