Sort Algorithm Part-1 Selection Sort

本文详细介绍了选择排序算法的基本概念,提供了ANSI C及C#两种语言的实现案例,并附带源代码,有助于读者深入理解该算法的工作原理及应用场景。

Sort Algorithm

Part -1

Selection Sort

 

 


Table of Contents. 2

1. Definition. 3

2. Implements in ANSI C. 3

2.1 List of c files. 3

2.2 Source code. 3

2.2.1 main.c 3

2.2.2 def.h. 3

2.2.3 sort.h. 3

2.2.4 sort.c 3

3. Implements in C#. 4

3.1 List of C# files. 4

3.2 Source code. 4

3.2.1 Main.cs. 4

3.2.2 Sorter.cs. 4

 


A sorting technique that is typically used for sequencing small lists. It starts by comparing the entire list for the lowest item and moves it to the #1 position. It then compares the rest of the list for the next-lowest item and places it in the #2 position and so on until all items are in the required order. Selection sorts perform numerous comparisons, but fewer data movements than other methods.

 

2.1 List of c files

  1. main.c
  2. def.h
  3. sort.h
  4. sort.c

2.2 Source code

2.2.1 main.c

#include <stdio.h>

#include <string.h>

#include "sort.h"

 

int main(int argc, char **argv) {

    Item itm[] = {"ASORTINGEXAMPLE"};

    s_sort(itm, 0, strlen(itm));

 

    return 0;

}

2.2.2 def.h

typedef char Item, *PItem;

 

#define less(a, b)  ((a) < (b))

#define exch(a, b)  {Item tmp; tmp = (a); (a) = (b); (b) = tmp;}

 

2.2.3 sort.h

#include "def.h"

 

void s_sort(Item*, int, int);

 

2.2.4 sort.c

#include "sort.h"

 

void s_sort(Item*, int, int);

 

void s_sort(Item item[], int l, int r) {

    int i;

 

    for (i = l; i < r - 1; i++) {

        int min = i, j;

 

        for (j = i + 1; j < r; j++) {

            if (less(item[j], item[min]))

                min = j;

        }

       

        exch(item[i], item[min]);

    }

}

 

 

3.1 List of C# files

  1. Main.cs
  2. Sorter.cs

3.2 Source code

3.2.1 Main.cs

using System;

using System.Collections;

 

namespace AlgorithmPractice {

    /// <summary>

    /// Summary description for TestClass.

    /// </summary>

    class TestClass {

        /// <summary>

        /// The main entry point for the application.

        /// </summary>

        [STAThread]

        static void Main (string[] args) {

            char[] charItem = {'A', 'S', 'O', 'R', 'T',

                                  'I', 'N', 'G', 'E', 'X',

                                  'A', 'M', 'P', 'L', 'E'};

 

            int[] intItem = new int[]{1, 5, 3, 6, 10,

                                         55, 9, 2, 87, 12,

                                         34, 75, 33, 47, 1};

 

            Sorter.SelectionSort(charItem, null, 0, charItem.Length);

            Sorter.SelectionSort(intItem, null, 0, intItem.Length);

 

            System.Diagnostics.Debug.WriteLine(new string(charItem));

        }

    }

}

 

3.2.2 Sorter.cs

using System;

using System.Collections;

 

namespace AlgorithmPractice

{

      /// <summary>

      /// Summary description for Sorter.

      /// </summary>

      public class Sorter

      {

            private Sorter(){}

 

        public static void SelectionSort(

            IList item, IComparer comparer,

            int l, int r) {

            if (null == comparer)

                comparer = Comparer.Default;

 

            for (int i = l; i < r - 1; i++) {

                int min = i;

                object tmp;

 

                for (int j = i + 1; j < r; j++)

                    if (comparer.Compare(item[j], item[min]) < 0)

                        min = j;

 

                tmp = item[i];

                item[i] = item[min];

                item[min] = tmp;

            }

        }

      }

}

 

### Selection Sort Algorithm Explanation Selection sort is a simple comparison-based sorting algorithm that divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right. This process continues iteratively until no elements remain in the unsorted part[^1]. #### Implementation Details The selection sort algorithm can be implemented as follows: 1. Start with an array `arr` containing `n` elements. 2. For each position `i` starting from 0 to `n-2`, find the minimum value within the subarray `arr[i..n-1]`. 3. Swap the found minimum value with the current element at index `i`. Below is the Python code implementing the selection sort algorithm: ```python def selection_sort(arr): n = len(arr) for i in range(n): # Iterate over all positions except the last one min_index = i # Assume the first element is minimal # Find the actual minimal element's index in the unsorted portion for j in range(i + 1, n): if arr[j] < arr[min_index]: min_index = j # If a new minimum was found, swap it with the current element if min_index != i: arr[i], arr[min_index] = arr[min_index], arr[i] return arr ``` In terms of performance analysis, selection sort has both its best-case and worst-case time complexity equal to O(n²). This makes it less efficient than more advanced algorithms like merge sort or quicksort when dealing with large datasets[^2]. However, due to its simplicity, it may still serve well under specific circumstances where computational resources are limited but sufficient enough for small-scale operations.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值