Sorting :

Definition :  Sorting is a process of storing data in sorted order. It can be done in both ascending and descending order. Sorting arranges the data in a sequence  which makes searching easier and saves  time and memory space.

Different Types  of Sorting  Algorithm :
1.Bubble Sort
2.Selection Sort
3.Insertion Sort
4.Quick Sort
5.Merge Sort
6.Heap Sort

Bubble Sort :  Bubble sort is one of the simplest sorting algorithm . It works by repeatedly swapping and comparing  the adjacent elements and moving the largest element to the highest index position (for ascending order ) of the array segment if they are placed in wrong order.  This process will continue till the entire array  is sorted. It can be sorted in both ascending and descending order.

If the elements are to be sorted in descending order, then in first pass the smallest element is moved to the highest index of the array.

Algorithm of Bubble Sort :
Bubblesort(a,n)
Step 1: Repeat Step 2 For 1 = 0 to n-1
Step 2:  Repeat For j = 0 to n - i
Step 3:  IF A[j] > A[j + 1]
SWAP A[j] and A[j+1]
[END OF INNER LOOP]
   [END OF OUTER LOOP]
Step 4: EXIT

C Program For Bubble Sort  On Code Blocks :

#include<stdio.h>
int main()
{
    int a[20],n,i,j,temp;
    printf("How many data do you want to     sort.\n");
    scanf("%d",&n);
    printf("Enter a number one by one.\n");
    for(i=0; i<n; i++)
        scanf("%d",&a[i]);
    for(i=0; i<n-1; i++)
    {
        for(j=0; j<n-1-i; j++)
        {
            if(a[j]>a[j+1])
            {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
            }
        }
    }
    printf("The sorted array. ");
    for(i=0; i<n; i++)
        printf("%d \n",a[i]);
    return 0;
}

Output Of The Program :

   


Post a Comment

Previous Post Next Post