Friday, 28 June 2013

Sorting of Elements Algorithim with explanation and program



ALGORITHM

VARIABLES:
§  i:     loop counter.
§  A:    name of array.
§  n:    number of elements of array.
§  pass:     for passing the value.


ALGORITHM:

STEP 1:    repeat step 2 & 3
                 For pass 1 to (n-1)
STEP 2:    i = 1
STEP 3:    repeat while
                 i <= n-pass

                 (a) if a [i]>a[i+1] then,
                 interchange a[i] & a[i+1]
                     (b) i = i+1
     STEP 4:   Exit

EXPLANATION:

§  To sort elements of an array, firstly repeat steps 2 & 3 for passes, the element for comparison from 1 to (n-1). Here, 1 is the very first element & (n-1) is the last element of the array.

§  Now, set the loop counter ‘i’ equal to 1 to start the sorting of the element in ascending or descending.

§  After setting loop counter ‘i’ equal to 1, repeat this step until ‘i’ is not greater than or equal to the element of array.
Now, compare the first element with second, and the smaller element will arrange itself in the first place. This comparison will repeat until all the elements of the array are sorted .

§  After comparing every element of the array with other, the loop counter ‘i’ is incremented by 1, each time it compare two values until the condition is satisfied

IMPLEMENTTION:


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[10],i,n,t,p,c;
printf("\nenter n");
scanf("%d",&n);
printf("\nenter array elements");
for(i=1;i<=n;i++)
{0
scanf("%d",&a[i]);
}
for(p=1;p<=n;p++)
{
if(a[i]>a[+1])
{
t=a[i];
a[i]=a[i+1];
}
}
printf("\nsorted array is");
for(i=1;i<=n;i++)
{
printf("\n%d",a[i]);
}
getch();
}

Flowchart of Sorting of elements


Definitin fo Array



“The collection of homogenous data elements stored under a single name in consecutive memory locations.”
This single name is called array. Individual elements of array are called SUB-SCRIPTED variables. Thus a sub-scripted variable consists of an array name followed by sub-script of an index enclosed in square bracket. A pair of bracket is used for sub-script. Array may be one dimensional one dimensional or two dimensional.
TYPES OF ARRAY:

        1.ONE DIMENSIONAL ARRAY
        2.TWO DIMENSIONAL ARRAY
§  ONE DIMENSIONAL ARRAY:
This type of array is also called linier array. In this, there is only one sub-script. Each element of array is stored in consecutive location in memory as
Data type  array name  size
                                                  int a[10] = (1,2,3,4,5,6,7,8,9,10)
§  TWO DIMENSIONAL ARRAY:
It is also called 2-D array. It is also called MATRIX because it contains rows and columns. This type of array consists of two sub-scripts. First sub-script represents rows and second sub-script represents columns. It is also called m*n matrix. Here, ‘m’ represents rows & ‘m’ represents columns.
EXAMPLE:
                     a [3] [3]
MEMORY REPRESENTATION
§  ROW BY ROW
§  COLUMN BY COLUMN