Selection Sort in DSA C++

Program 1

// Implementation of Selection Sort
#include<iostream>
using namespace std;
int main()
{
    system("cls");
      int ar[500],n,i,j,temp,min,loc;
      cout<<"\n Enter the limit: ";
      cin>>n;
      if(n<0 || n>500)
         cout<<"\n Invalid limit";
      else
      {
        cout<<"\n Enter elements in array: ";
        for(i=0;i<n;i++)
             cin>>ar[i];

         // Selection sort     
        for(i=0;i<n;i++)     
        {
               min=ar[i];
               loc=i;
            for(j=i+1;j<n;j++)    
            {
                  if(ar[j]<min)
                  {
                       min=ar[j];
                       loc=j;
                  }
            }
          if(i!=loc)
          {
              temp=ar[i];
              ar[i]=ar[loc];
              ar[loc]=temp;
          }   
        }
      cout<<"Sorted element is : ";
      for(i=0;i<n;i++)  
      cout<<"\n"<<ar[i];
      }   

    return 0;
}

 

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *