[英]Insertion sort - counting of comparisons and swaps in C
如何計算插入排序中的比較和交換次數? 我有 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;
}
這是使用插入排序對數組進行排序並計算最佳、平均和最壞情況的比較次數的代碼。
#include<iostream>
using namespace std;
int insertionsort( int arr[ ], int n)
{
int i,temp,j;
int comp=0;
for( i=1; i<n ; i++ )
{
temp=arr[i];
j = i - 1;
while( j>=0 && temp<arr[j])
{
arr[j+1] = arr[j] ;
j = j-1 ;
comp++;
}
arr[j+1]=temp;
if(temp>arr[j])
{
comp++;
}
}
return comp;
}
void display( int arr[ ], int n, int comp )
{
cout<<" Elements of array after sorting "<<endl;
for( int i=0; i<n; i++ )
{
cout<<arr[i]<<" ";
}
cout<<endl;
cout<<" Number of comparisions "<<comp<<endl;
}
int main()
{
int size;
int comp = 0;
cout << " Enter the size of an array " << endl;
cin >> size;
int arr[size];
int n= sizeof(arr) / sizeof(arr[0]);
cout<<" Enter the elements of array "<<endl;
for( int i=0; i<size; i++ )
{
cin>>arr[i];
}
cout<<" Elements of array before sorting "<<endl;
for( int i=0; i<size; i++ )
{
cout<<arr[i]<<" ";
}
cout<<endl;
int compairsion = insertionsort( arr, n);
display( arr, n, compairson);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.