Slip 3_1 : Sort a random array of n integers (accept the value of n from user) in ascending order by using insertion sort algorithm.

 Solution :
/* Insertion sort on random nos */
#include<stdio.h>
int main()
{
 int a[10],i,j,n,key;
 printf("Enter how many numbers: ");
 scanf("%d",&n);
 for(i=0; i<n; i++)
 {
 a[i]=rand()%100;
 }
 printf("\n Before sorting array is ");
for(i=0;i<n;i++)
 {
 printf("%d ",a[i]);
 }
 for(i=1; i<n; i++)
 {
 key = a[i];
 for(j=i-1; j>=0; j--)
 {
 if(a[j] > key)
 {
 a[j+1]=a[j];
 }
 else
 break;
 }
 a[j+1]=key;
 }
 printf("\nAfter sort array is: ");
 for(i=0; i<n; i++)
 {
 printf("%d ",a[i]);
 }
}

Comments

Popular posts from this blog

Slip 22_2: Read the data from file 'cities.txt' containing names of cities and their STD codes. Accept a name of the city from user and use sentinel linear search algorithm to check whether the name is present in the file and output the STD code, otherwise output “city not in the list”. Solution :

Slip10_2, 30_1 : Read the data from the file “employee.txt” and sort on names in alphabetical order (use strcmp) using bubble sort or selection sort

Slip 23_2: Read the data from file ‘sortedcities.txt’ containing sorted names of cities and their STD codes. Accept a name of the city from user and use binary search algorithm to check whether the name is present in the file and output the STD code, otherwise output “city not in the list”.