Sorting Program in C
Bubble
Sort
// Bubble Sort Code
#include <stdio.h>
void main()
{
int array[100], n, c, d, swap;
printf("Enter number of
elements\n");
scanf("%d", &n);
printf("\n\t BUBBLE
SORT");
printf("\n\t
===========");
printf("Enter %d
integers\n", n);
for (c = 0; c < n; c++)
scanf("%d",
&array[c]);
for (c = 0 ; c < ( n - 1 );
c++)
{
for (d = 0 ; d
< n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For
decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1]
= swap;
}
}
}
printf("Sorted list in
ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
getch();
}
Insertion
Sort
// WAP of Insertion Sort
#include <stdio.h>
void main()
{
int n, array[100], c, d, t;
clrscr();
printf("\n\t INSERTION
SORT");
printf("\n\t
==============");
printf("\nEnter number of
elements\n");
scanf("%d", &n);
printf("Enter %d
integers\n", n);
for (c = 0; c < n; c++) {
scanf("%d",
&array[c]);
}
for (c = 1 ; c <= n - 1;
c++)
{
d = c;
while ( d > 0
&& array[d-1] > array[d])
{
t
= array[d];
array[d]
= array[d-1];
array[d-1] = t;
d--;
}
}
printf("Sorted list in
ascending order:\n");
for (c = 0; c <= n - 1; c++)
printf("%d\n",
array[c]);
getch();
}
Shell
Sort
/*
* C Program to sort an array
using Shell Sort technique
*/
#include <stdio.h>
void shellsort(int arr[], int num)
{
int i, j, k, tmp;
for (i = num / 2; i > 0; i
= i / 2)
{
for (j = i; j < num; j++)
{
for(k = j - i; k
>= 0; k = k - i)
{
if (arr[k+i]
>= arr[k])
break;
else
{
tmp = arr[k];
arr[k] =
arr[k+i];
arr[k+i] =
tmp;
}
}
}
}
}
int main()
{
int arr[30];
int k, num;
clrscr();
printf("\n\t
SHELL SORT");
printf("\n\t
==========");
printf("\nEnter
total no. of elements : ");
scanf("%d",
&num);
printf("\nEnter %d
numbers: ", num);
for (k = 0 ; k < num; k++)
{
scanf("%d",
&arr[k]);
}
shellsort(arr, num);
printf("\n Sorted array
is: ");
for (k = 0; k < num; k++)
printf("%d ",
arr[k]);
return 0;
}
Comments
Post a Comment