简体   繁体   English

有人可以解释一下这个排序算法是如何工作的,这个算法的名称是什么?

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

I have created a sorting function.我创建了一个排序功能。 Can I know the name of this algorithm?我能知道这个算法的名字吗? Is this bubble sort?这是冒泡排序吗?

I am new in C.我是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;
            }
        }
    }
}

No it's not bubble sort .不,这不是冒泡排序 It doesn't compare adjacent elements nor implements any check to stop traversing if the array becomes sorted.如果数组已排序,它不会比较相邻元素,也不会执行任何检查以停止遍历。

It's similar to exchange sort , which could be implemented like the following (note the differences, though):它类似于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] */
        }
    }
}

I'd argue that the posted algorithm is much more similar to insertion sort .我认为发布的算法与插入排序更相似。 See how it transforms the array:看看它如何转换数组:

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

I don't think it has a name, but it's described in this paper: "Is this the simplest (and most surprising) sorting algorithm ever?"我不认为它有名字,但它在这篇论文中有所描述: “这是有史以来最简单(也是最令人惊讶)的排序算法吗?” Stanley PY Fung史丹利冯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM