Selection Sort

//Code

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
void selectionSort(int *p,int n)
{
int min_index;
for(int i=0;i<n-1;i++)
//last value ke liye loop nh chalana hai kyuki vo end mai 
//correct position pai aa jaegi
{  min_index=i;
for(int j=i+1;j<n;j++)
//har value ko baki n-1 values se comapre krega.
{
if(p[j]<p[min_index])
{
swap(p[min_index],p[j]);
}


}
}
}
main()
{

int a[]={5,4,7,8,2,1,9,10,6,3};
int n=sizeof(a)/sizeof(a[0]);
selectionSort(a,n);
printf("Sorted Array\n");
for(int i=0;i<n;i++)
{
printf("%d ",a[i]);
}

}
--------------------------------------------------------------------------------------------------------------------------
/*Alternatively you can use this method for user input

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
void selectionSort(int *p,int n)
{
int min_index;
for(int i=0;i<n-1;i++)
//last value ke liye loop nh chalana hai kyuki vo end mai 
//correct position pai aa jaegi
{  min_index=i;
for(int j=i+1;j<n;j++)
//har value ko baki n-1 values se comapre krega.
{
if(p[j]<p[min_index])
{
swap(p[min_index],p[j]);
}


}
}
}
main()
{
int n;
   printf("Enter Size of Array\n");
   scanf("%d",&n);
   printf("Enter the %d elements of array\n",n);
int *arr;
arr=(int*)malloc(100*sizeof(int));
//we can use either calloc or malloc.Syntax of calloc is
//arr=(int*)calloc(n,sizeof(int)); here you save the memory
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
selectionSort(arr,n);
printf("Sorted Array\n");
for(int i=0;i<n;i++)
{
printf("%d ",arr[i]);
}


}*/

No comments:

Post a Comment