Sorting in C Language
Sorting is a process in which we
rearrange the elements in any particular order, which can be set ready for
further processing by the program logic. In C programming language, there are
multiple sorting algorithms available, which can be incorporated inside the
code. The various types of sorting methods possible in the C language are
Bubble sort, Selection sort, Insertion sort, Quick sort, Merge sort and Heap
sort.
Bubble Sort
It is the simplest sorting method
in which program algorithm swap the adjacent elements if they are in the wrong
order. This method is not suitable for large data sets as its average and
worst-case time complexity is quite high. There are n-1 passes and cycle
required. For Example we can see the diagram – (sorting in ascending order)
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int arr[100], n, i, j, t;
//Taking input of arr size
printf("Enter number of elements :");
scanf("%d",&n);
//taking input of array elements
printf("Enter %d elements of array\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
//sorting (bubble)
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1]) /* For decreasing order use '<' instead of '>' */
{
//swaping
t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}}}
//printing sorted element
for(i=0;i<n;i++)
{
printf("%d\n",arr[i]);
}
getch();
}