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

Selection Sort: Algorithm

Selection sort and insertion sort are sorting algorithms. Selection sort works by iterating through an array, finding the smallest element, and swapping it into the current slot. Insertion sort iterates through an array and inserts each element into its sorted position. Both algorithms are demonstrated with pseudocode that repeats steps to iterate through array elements and swap or insert them into sorted order.

Uploaded by

Aman Qureshi
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)
75 views2 pages

Selection Sort: Algorithm

Selection sort and insertion sort are sorting algorithms. Selection sort works by iterating through an array, finding the smallest element, and swapping it into the current slot. Insertion sort iterates through an array and inserts each element into its sorted position. Both algorithms are demonstrated with pseudocode that repeats steps to iterate through array elements and swap or insert them into sorted order.

Uploaded by

Aman Qureshi
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

Selection sort

Algorithm:
1) Repeat step 2 and 3 for K=1 to n-1
2) Call smallest (arr ,k,n,pos)
3) Swap a[k] with arr[pos]
4) Exit
Smallest(arr,k,n,pos)
1) Set small = arr[k]
2) Set pos=k
3) Repeat for j=k+1 to n-1
If small>arr[j]
Set pos=j
[end of if]
[end of loop]
4) Exit

Program:

int smallest(intarr[],intk,int n)
{
intsmall,j,pos;
small=arr[k];
pos=k;
for(j=k+1;j<n;j++)
{
if(small>arr[j])
{
small=arr[j];
pos=j;}}
return pos;
}

main()
{
int i,arr[6],k,c,temp;
[Link]("Enter 6 numbers: ");
for(i=0;i<6;i++)
{
Scanner sc=new Scanner([Link]);
arr[i] = [Link]();
}
for(i=0;i<6;i++)
{
c=smallest(arr,i,6);
temp=arr[i];
arr[i]=arr[c];
arr[c]=temp;
}
for(i=0;i<6;i++)
{
[Link]("%d ",arr[i]);}
}

Insertion Sort

Algorithm:
1) Repeat step 2 to 5 for K=1 to n-1
2) Set temp=arr[k]
3) Set j=k-1
4) Repeat while temp <=arr[j]&&j>=0
Set arr[j+1]=arr[j]
Set j=j-1
5) Set arr [j+1] = temp
6) Exit
Program
voidinsertion_sort(int a[]) main()
{ {
intk,j,temp,n; int arr[10],i;
n=10; [Link]("Enter the elements of the
for(k=1;k<=(n-1);k++) array");
{ for(i=0;i<10;i++)
temp=a[k]; {
j=k-1; Scanner sc=new Scanner([Link]);
while(temp<=a[j] && j>=0) arr[i] = [Link]();
{ }
a[j+1]=a[j]; insertion_sort(arr);
j=j-1; }
}
a[j+1]=temp;
}
[Link]("sorted array is:");
for(k=0;k<10;k++)
{ [Link]("%d\n",a[k]);
}

You might also like