SAVITIBAI PHULE UNIVERSITY OF PUNE
S. Y. B.B.A. (C.A.) Semester III
Practical Examination
Lab Course: (CA-306) Computer Laboratory Based on 302, 304 and 305
Data Structure, Angular JS/ PHP, Big Data / Block Chain
/*
Q.1 B) Write a 'C' program to sort randomly generated array elements using insertion sort method.
(Use Random Function)
*/
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
// CheckFor: Create new Array
void CreateArray(int A[], int n){
// CheckFor: Declaration of local variable
int i = 0;
// LoopFor: Assingn the random array elements
for ( i = 0; i < n; i++)
A[i] = rand();
}
// CheckFor: Display the Array
void DisplayArray(int A[], int n){
// CheckFor: Declaration of local variable
int i = 0;
// LoopFor: Display the array elements
for ( i = 0; i < n; i++)
printf("%d \t", A[i]);
}
// CheckFor: Sort the Array Element using Insertion Sort Algorithm
void InsertionSort(int A[], int n){
// CheckFor: Declaration of local variable
int i = 0, j = 0, key = 0;
// LoopFor: Moving the Array from first to last element
for( i = 1; i < n; i++){
// CheckFor: Assign the first element of unsorted array for the key
key = A[i];
// LoopFor: Check the accurate position of the key element.
for( j = i-1; (j >= 0) && (key < A[j]); j--){
A[j+1] = A[j];
}
// CheckFor: Place the accurate position of the key element.
A[j+1] = key;
}
// CheckFor: Display the Sorted Array
printf("\n\nThe Sorted Array after Insertion Sort is: \n\n");
for ( i = 0; i < n; i++)
printf("%d \t", A[i]);
}
int main(){
int A[MAX], num = 0;
// Accept the n number from user
printf("Enter How many element we want to in array: ");
scanf("%d", &num);
// create n random element array
CreateArray(A, num);
// Display the given array
printf("\n\nThe given array elements are: \n\n");
DisplayArray(A, num);
// Sort the element using insertion sort algorithm
InsertionSort(A, num);
printf("\n\n");
system("pause");
return 0;
}
No comments:
Post a Comment