Selection Sort algorithm
A is an array of n elements to be sorted.
Step 1: set LOC=0
Step 2: Repeat step 3 and 4 for K=0 to n-1
Step 3: LOC = Call Min(A,K,n)
Step 4: [Interchange A[K] and A[LOC])
temp = A[K]
A[K]=A[LOC]
A[LOC]=temp
Step 5: Exit
Program to Sort n numbers using Selection Sort:
int min(int a[], int k, int n)
{
int loc,j,min;
min=a[k];
loc=k;
for(j=k+1;j<=n-1;j++)
if(min=a[j])
{
min=a[j];
loc=j;
}
return (loc);
}
void main()
{
int i,a[100],k,n,loc=0,temp;
printf(“Enter the number of elements:\n”);
scanf(“%d”,&n);
printf(“Enter the array elements:\n”);
for(i=0;i<n;i++)
scanf(“%d”,&n);
printf(“Enter the array elements:\n”);
for(i=0;i<n;i++)
{
loc=min(a,k,n);
temp=a[k];
a[k]=a[loc];
a[loc]=temp;
}
printf(“The Sorted array is:\n”);
for(i=0;i<n;i++)
printf(“%d”,a[i]);
}
Bubble Sort Algorithm
A is an array of n elements to be sorted.
Step 1: for pass = 1 to n-1
Step 2: for j=0 to n-pass-1
Step 3: if a[j]>a[j+1] then
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
Step 4: End for
Step 5: End for
Program for sort ‘n’ numbers using Bubble Sort:
#include<stdio.h>
void bubble_sort(int a[], int n)
{
int pass, temp,j;
for(pass=1;pass<n;pass++)
{
for(j=0;j<=n-pass-1;j++)
{
if(a[j]>a[j+1})
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
int main()
{
int i,j,a[20],n,temp;
printf(“Enter the number of elements:\n”);
scanf(“%d”,&n);
printf(“Enter the array elements:\ n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
bubble_sort(a,n);
printf(“The sorted elements are:\n”);
for(i=0;i<n;i++)
printf (“%d”,a[i]);
}