0% found this document useful (0 votes)
4 views2 pages

Algorithms

The document describes the Selection Sort and Bubble Sort algorithms for sorting an array of n elements. It provides step-by-step instructions and sample code for implementing both sorting methods in C. Each algorithm iterates through the array to arrange the elements in ascending order.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Algorithms

The document describes the Selection Sort and Bubble Sort algorithms for sorting an array of n elements. It provides step-by-step instructions and sample code for implementing both sorting methods in C. Each algorithm iterates through the array to arrange the elements in ascending order.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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]);
}

You might also like