Selection sort

From Algorithmist
Jump to: navigation, search
Sorting
Algorithms
Bubble sort
Insertion sort
Selection sort
Quicksort
Merge sort
Heap sort
Introsort
Counting sort
Problems
Problems solvable using sorting

With selection sort, you essentially take the smallest entry from the unsorted portion of an array and build a sorted array at the front, entry by entry.

Algorithm[edit]

  1. At each iteration find the smallest entry (the "key") in the unsorted portion of the array.
  2. Swap the "key" with the the ith entry.


Pseudo-code[edit]

  • lst is an array
func selsrtI(lst)
    max = length(lst) - 1

    for i from 0 to max
        key = lst[i]
        keyj = i

        for j from i+1 to max
            if lst[j] < key
                key = lst[j]
                keyj = j

        lst[keyj] = lst[i]
        lst[i] = key

    return lst

end func

Using C[edit]

  • n is no. of element in array
printf("\nEnter the values:\n");
for(i=1;i<=n;i++)
    scanf("%d",&a[i]);
for(i=1;i<=n;i++)
{                
   	min=i;
   	for(j=i+1;j<=n;j++)
       	{
  		if (a[min]>a[j])
  		   min=j;
        }
   	if(min!=i)
       	{
       	  t=a[i];
          a[i]=a[min];
          a[min]=t;
       	}
}
printf("\nSorted list in ascending order:\n");
for(i=1;i<=n;i++)
    printf("%d\n",a[i]);