1. 程式人生 > >小橙書閱讀指南(二)——選擇排序

小橙書閱讀指南(二)——選擇排序

sel alt 代碼示例 運行時間 mon cti override 和數 integer

算法描述:一種最簡單的排序算法是這樣的:首先,找到數組中最小的那個元素,其次,將它和數組的第一個元素交換位置。再次,再剩下的元素中找到最小的元素,將它與數組的第二個元素交換位置。如此往復,知道將整個數組排序。這種方法叫做選擇排序,因為它在不斷地選擇剩余元素之中的最小者。

算法圖示:

技術分享圖片

Java代碼示例:

import common.ArraysGenerator;
import common.Sortable;

import java.io.IOException;
import java.util.Arrays;

public class Selection implements Sortable<Integer> {

    @Override
    
public void sort(Integer[] array) { for (int i = 0; i < array.length; ++i) { int minIndex = i; for (int j = i + i; j < array.length; ++j) { if (array[j] < array[minIndex]) { minIndex = j; } }
int tmp = array[minIndex]; array[minIndex] = array[i]; array[i] = tmp; } } public static void main(String arg[]) throws IOException { Integer[] arr = ArraysGenerator.fromFile("disorder.txt", 1000000); Selection selection = new Selection();
long start = System.currentTimeMillis(); selection.sort(arr); long end = System.currentTimeMillis(); System.out.println(Arrays.toString(arr)); System.out.println(end - start); } }

Qt/C++代碼示例:

void Selection::sort(int * arr, int len)
{
    for (int i = 0; i < len; ++i) {
        int minIndex = i;
        for (int j = i + 1; j < len; ++j) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        int tmp = arr[minIndex];
        arr[minIndex] = arr[i];
        arr[i] = tmp;
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // 從文件中讀取數組的方法,指定文件名與數組長度,返回數組指針
    int *arr = Arrays::fromFile("disorder.txt", 1000000);

    Selection selection;

    QTime rt;
    
    rt.start();
    selection.sort(arr, 1000000);
    int el = rt.elapsed();

    qDebug() << el;
    return a.exec();
}

總的來說,選擇排序是一種很容易理解和實現的簡單排序算法,它有兩個很明顯的特點——運行時間和輸入無關。

小橙書閱讀指南(二)——選擇排序