Linear sort with Psuedo code and a program Complete Explanation

Hello Guys in this blog I am going to make a Linear sort algorithm and its psuedo code. And step by step Explanation of it. So lets start. 

Linear Sort : Its an algorithm in which most smallest number of an array will be on the top of its first cycle. And on every cycle one by one each and every number will be arranged in sorted manner. For using Linear Sort our motive is to sort the number in any given array in sorted manner may be in ascending or descending.

What is required to implement LinearSort ?
A series of numbers which will be used for comparison of data in array.

And example of number series for an array of 4 elements.
e  f
0 1  
0 2
0 3
0 4
1 2
1 3
1 4
2 3
2 4
3 4

So this is the number series which is required to sort an array of 4 elements
Explanation :  Here you are thinking how number could be sorted only through this number series.
int x[]={4,2,5,1};
when e=0,f=1 we are in inner loop 
and 
compairing the value on x[e] and x[f]  is x[e]>x[f] (4>2)yes then swap, after swaping array is {2,4,5,1}
Now e=0 and f=2
compairing the value on x[e] and x[f]  is x[e]>x[f](2>5) No, then do nothing.
Now e=0 and f=3
compairing the value on x[e] and x[f]  is x[e]>x[f](2>1) yes, then swap x[e] and x[f] then the array is {1,,4,5,2}
The first cycle is completed and smallest number is on the top.
Like this e=1 and f=2 and so on....... 
at last when e=4 loops condition will be false and your array will be sorted.

Pseudo Code : 

[Initialization] 

1. we have to take two variable which will generate the number series lets take it e and f;

2. And then initialize e with lower bound or 0;

[Looping]

1. In this algorithm we should have to use nested loop technique to generate the above number series.

2. for(e=0;e<upperBound-1;e++) this is the first loop which will be continue untill e is not equal to upperBound.

3. And an inner loop inside the above loop. in which for(f=e+1;f<upperBound;f++), f would also be e+1 because it is comparing the data of whole data of array with the data on e one by one.

[Comparisons]

1. After making the nested loops then we have to make comparisons so in the inner loop we will apply a if(x[e]>x[f]) then swap the values on e and f.

2. That's all this is the code of linear sort.


Linear Sort Code in C Language : 

#include<stdio.h>

int main()
{
int x[10],y,lb,ub;

for(y=0;y<10;y++) 
{
printf("Enter a number : ");
scanf("%d",&x[y]);
}

int e,f,g=0;
lb=0;
ub=10;

for(e=0;e<ub-1;e++)
{
for(f=e+1;f<ub;f++)
{
if(x[f]<x[e])
{
g=x[f];
x[f]=x[e];
x[e]=g;
}
}
}

for(y=0;y<=9;y++) printf("%d\n",x[y]);

return 0;
}

Comments

Popular Posts