/*
* At every iteration, this sorting finds the smallest element
* in the unsorted subarray and place it in its correct location.
* Initially the full array = unsorted subarray. If an array has
* n elements, after 1 iteration, the unsorted subarray contains
* n-1 elements ( all elements except the smallest one,which is
* placed at index 0)
*/
#include<stdio.h>
int main(void)
{
int i,n,arr[20],j;
int min,pos,temp;
printf("Enter the element size:");
scanf("%d",&n);
printf("Enter the array elements:");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
{
//Assume ith element to be min
min=arr[i];
//Compare with all other elements to find the minimum one
for(j=i+1;j<n;j++)
{
if(arr[j]<min)
{
min=arr[j];
pos=j;
}
}
//If assumed min is not equal to actual min
// swap their locations
if(min!=arr[i])
{
temp=arr[i];
arr[i]=min;
arr[pos]=temp;
}
}
printf("The sorted array\n");
for(i=0;i<n;i++)
printf("%d ",arr[i]);
return 0;
}
Written by Munia Balayil
* At every iteration, this sorting finds the smallest element
* in the unsorted subarray and place it in its correct location.
* Initially the full array = unsorted subarray. If an array has
* n elements, after 1 iteration, the unsorted subarray contains
* n-1 elements ( all elements except the smallest one,which is
* placed at index 0)
*/
#include<stdio.h>
int main(void)
{
int i,n,arr[20],j;
int min,pos,temp;
printf("Enter the element size:");
scanf("%d",&n);
printf("Enter the array elements:");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
{
//Assume ith element to be min
min=arr[i];
//Compare with all other elements to find the minimum one
for(j=i+1;j<n;j++)
{
if(arr[j]<min)
{
min=arr[j];
pos=j;
}
}
//If assumed min is not equal to actual min
// swap their locations
if(min!=arr[i])
{
temp=arr[i];
arr[i]=min;
arr[pos]=temp;
}
}
printf("The sorted array\n");
for(i=0;i<n;i++)
printf("%d ",arr[i]);
return 0;
}
Written by Munia Balayil
No comments:
Post a Comment