Algorithm-Selection sort


Selection sort algorithm


An algorithm is any part of a program that needs designated steps to accomplish. In "Introduction to Software Develop" page, we present the Parking Fee algorithm by using pseudo-code and flowchart.

Data Structure is a group of elements and their relationship. The examples of data structure are array, structure, linked list, stack, and queue.

In this page and the next pages, we will discuss some common techniques used to sort and search elements in array data structure. And after that we will discuss linked list, stack, and queue data structures. The array data structure is not discussed here and the next pages of this subject because we already discussed them in many programming languages tutorials in this web site.

Sorting algorithm

Sorting is one of the most common task in computer science. It is the process to apply rank to a set of data (data structure). Imagine that you work with 100 grades of students. How do you find the smallest grade or the highest grade if the data set is unsorted?

Selection Sort Algorithm
In the selection sort, the data set is divided into two sub-lists: sorted list and unsorted list. The smallest value of the unsorted list is determined and swapped to the beginning of the unsorted list. Then the number of sorted list increases by one and the number of unsorted list deceases by one. Each time we move one element from the unsorted list to the sorted list, we call sort pass. The number of passes is equal to the number of the data points in the data set minus one. If we have n data points the number of passes to complete the sort process is n-1.

Example C++ code for selection sort:


#include <cstdlib>
#include <iostream>
#include <conio.h>


using namespace std;
void selectsort(int A[],int n){
  int i,j,min;
  for(i=0;i<n;i++){
    min=i;
    for(j=i+1;j<n;j++)
      if(A[j]<A[min]) min=j; //find min value
    //swapping
   int temp=A[i];
   A[i]=A[min];
   A[min]=temp;

   }

}

int main(int argc, char *argv[])
{
  int A[]={23,4,45,23,12,2};
  selectsort(A,6);
  for(int i=0;i<6;i++)
    cout<<A[i]<<endl;

  getch();
  return 0;
}




Comments

CAPTCHA image



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.