Algorithm backup ---- Selection sort(选择排序算法)

  Selection sort is also a sorting algorithm, specifically an in-place comparisonsort. It has O(n2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations.

  The algorithm works as follows:

  1. Find the minimum value in the list/array

  2. Swap it with the value in the first position

  3. Repeat the steps above for the remainder of the list (starting at the second position and advancing each time)

  Effectively, we divide the list or array into two parts: the sublist of items already sorted, which we build up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array.

  Below is the implementation of this algorithm using C#:

/// <summary>
/// Selection sort algorithm
/// </summary>
/// <param name="numbers">numbers array to be sorted</param>
public static void SelectionSort(int[] numbers)
{
    
for (int i = 0; i < (numbers.Length - 1); i++)
    {
        
int min = i;
        
//find the smallest number starting from subscript 'i+1'
        
//and then change with numbers[i]
        for (int j = (i + 1); j < numbers.Length; j++)
        {
            
if (numbers[j] < numbers[min])
            {
                min 
= j;
            }
        }
        
if (i != min)
        {
            
int temp = numbers[i];
            numbers[i] 
= numbers[min];
            numbers[min] 
= temp;
        }
    }
}

 

Go to my home page for more posts

posted on 2009-11-03 16:35  lantionzy  阅读(257)  评论(0编辑  收藏  举报