Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Showing posts with label Sort Analysis. Show all posts
Showing posts with label Sort Analysis. Show all posts

Wednesday, 27 March 2019

SortAnalysis Aglorithm

ALGORITHM SortAnalysis(A[0..n - 1])

//Input: An array A[0..n - 1] of n orderable elements
//Output: The total number of key comparisons made
count ← 0
for i ← 1 to n - 1 do
v ← A[i]
j ← i - 1
while j ≥ 0 and A[j] > v do
count ← count + 1
A[j + 1] ← A[j]
j ← j - 1
A[j + 1] ← v
return count

C program:

#include<stdio.h>
int main(){
int n,v,i,j,count=0,arr[100];
printf("Enter the No element u want to enter\n");
scanf("%d",&n);
printf("Enter the Elements\n");
for(i=0;i<n;i++){
    scanf("%d",&arr[i]);
}
for(i=1;i<n;i++)
{
    v=arr[i];
    j=i-1;
    while(j>=0 && arr[j]>v){
        count++;
        arr[j+1]=arr[j];
        j--;
        arr[j+1]=v;
    }

}
for(i=0;i<n;i++)
{
    printf("%d, ",arr[i]);
}
printf("\nNo of Steps:%d\n",count);
}


Output:

Enter the No element u want to enter
5
Enter the Elements
1
32
54
6
4
1 ,4, 6, 32, 54
No of Steps:5