簡體   English   中英

有人可以解釋一下這個排序算法是如何工作的,這個算法的名稱是什么?

[英]Can someone explain me how this sorting algo is working, and what is the name of this algorithm?

我創建了一個排序功能。 我能知道這個算法的名字嗎? 這是冒泡排序嗎?

我是C的新手。

#include <stdio.h>

void sort(int *, int);

int main(void) {
    int arrayNum[] = {1, 12, 8, 4, 90, 11, 76};
    int len = sizeof(arrayNum) / sizeof(arrayNum[0]);
    sort(arrayNum, len);
    for (int i = 0; i < len; i++) {
        printf("%d, ", arrayNum[i]);
    }
    
    return 0;
}

void sort(int *array, int length) {
    int temp;
    for (int i = 0; i < length; i++) {
        for (int j = 0; j < length; j++) {
            if (array[i] < array[j]) {
                temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
    }
}

不,這不是冒泡排序 如果數組已排序,它不會比較相鄰元素,也不會執行任何檢查以停止遍歷。

它類似於exchange sort ,可以像下面這樣實現(但請注意差異):

for (int i = 0; i < length; i++) {
    // At every step, searches the minimum of the remaining elements     
    for (int j = i + 1; j < length; j++) {
        //       ^^^^^                          It doesn't touch the already sorted
        if ( array[j] < array[i] ) {
            //    ^^^        ^^^                To sort the array in ascending order
            /* swap array[j] and array[i] */
        }
    }
}

我認為發布的算法與插入排序更相似。 看看它如何轉換數組:

Starting point
1, 12, 8, 4, 90, 11, 76

Swaps 1 with 12 and then 12 with 90.
90,   1, 8, 4, 12, 11, 76

Swaps 90 with 1.
1, 90,   8, 4, 12, 11, 76

Swaps 90 and 8. In other words, it "inserts" 8 in an already sorted partition.
1, 8, 90,   4, 12, 11, 76

Inserts 4 (it first swaps 8 and 4, then 90 and 8).
1, 4, 8, 90,   12, 11, 76

Inserts 12 (swaps 90 and 12).
1, 4, 8, 12, 90,   11, 76

Inserts 11 (swaps 12 and 11, then 90 and 11).
1, 4, 8, 11, 12, 90,   76

Inserts 76 (swaps 90 and 76), then ends.
1, 4, 8, 11, 12, 76, 90

我不認為它有名字,但它在這篇論文中有所描述: “這是有史以來最簡單(也是最令人驚訝)的排序算法嗎?” 史丹利馮

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM