Google Search

Saturday, October 24, 2015

INSERTION SORT using C++

‪#‎include‬<stdio.h>
int fill_array(int a[], int size, int& n);
void insertion_sort(int a[], int size, int n);
void count_array(int a[], int counter[], int n);
int count = 0;
int main()
{
printf("\nThis program sorts numbers from lowest to highest.\n");
int a[100], n;
int counter[100] = {0};
fill_array(a, 100, n);
count_array(a, counter, n);
insertion_sort(a, 100, n);
printf("\n");
printf("\n");
printf("Numbers\t");
printf("Times \n");
for (int i = 0; i< n; i++)
{
printf("%d ",a[i]);
printf("%d",counter[i]);
}
printf("\n");
printf("\n");
printf("\nYou entered %d numbers",count);
return 0;
}
int fill_array(int a[], int size, int& n)
{
printf("\nEnter up to %d nonnegative whole numbers.\n",size);
printf("Mark the end of the list with a negative number.\n");
int next, i= 0;
scanf("%d",&next);
while ((next >= 0) && (i< size))
{
a[i] = next;
i++;
scanf("%d",&next);
count++;
}
n=i;
return count;
}
void insertion_sort(int a[], int size, int n)
{
int key,i;
for (n=1; n<size; n++)
{
key=a[n];
i=n-1;
while(a[i]>key && i>=0)
{
a[i+1]=a[i];
i--;
}
a[i+1]=key;
}
}
void count_array(int a[], int counter[], int n)
{
for(int i=0; i<n; i++)
{
for(int j=0;j<n;j++)
{
if(a[i]==a[j])
counter[i]++;
}
}
}

No comments:

Post a Comment