简体   繁体   English

这是插入排序还是冒泡排序?

[英]Is this insertion sort or bubble sort?

For a programming exam, I was asked to make an insertion sort algorithm to order numbers the teacher gave us. 对于编程考试,我被要求制作一个插入排序算法来排序老师给我们的数字。

I thought I nailed it. 我以为我钉了钉子。 It maybe wasn't the shortest algorithm possible, but I did my best, and it sorted as was asked for. 它可能不是最短的算法,但我已尽力而为,并按要求进行了排序。

The thing is, my teacher told me that I did a bubble sort instead of an insertion sort, and refuses to check it again. 问题是,我的老师告诉我,我做了冒泡排序,而不是插入排序,并且拒绝再次检查。 I'm pretty sure it is an insertion sort. 我很确定这是一种插入排序。

Could you tell me what you think? 你能告诉我你的想法吗?

We are suppose to show first the unordered array, then the steps and finally the ordered array. 我们假设首先显示无序数组,然后显示步骤,最后显示有序数组。

#include "stdafx.h"
#include "iostream"

using namespace std;

int _tmain(int argc, _TCHAR* argv[]) {

    double killme[34] = {7,5,6,5,78,9,63,36,32,5,78,63,2,1,9,45,23,32,21,45,78,32,58,23,36,41,23,45,21,45,6,9,36,7};   

    cout << "Arreglo desordenado: \n";

    for (int i = 0; i < 34; i++) {
        if(i != 33) {
            cout << killme[i] << ", ";
        }
        else {
            cout << killme[i] << ".";
        }
    }

    cout << endl;
    cout << endl;
    cout << "Pasos: " << endl;
    double var;
    int j = 1;
    int k = 0;

    for (int i = 0; i < 33; i++) {
        if (killme[i+1] < killme[i]) {
            while (killme[i+1] < killme[i]) {
                var = killme[i];
                killme[i] = killme[i+1];
                killme[i+1] = var;
                i--;
                if (i<0) {
                    break;
                }
            }

            for (int i = 0; i < 34; i++) {
                if (i != 33) {
                    cout << killme[i] << ",";
                }
                else {
                    cout << killme[i] << ".";
                }
            }

            cout << endl;
            cout << endl;
        }

        i = k;
        k++;
    }

    cout << "Arreglo ordenado: \n";

    for (int i = 0; i < 34; i++) {
        if (i != 33) {
            cout << i+1 << "." << killme[i] << ", " << endl;
        }
        else {
            cout << i+1 << "." << killme[i] << "." << endl;
        }
    }

    cout << endl;
    system("PAUSE");
    return 0;
}

Output 1 输出1

OUTPUT1

Output 2 输出2

OUTPUT2

Output 3 输出3

OUTPUT3

This is insertion sort. 这是插入排序。 well its very primitive. 很好,很原始。 as you can see it take each element and trys to find its place by comparing between element before and after it using for looping 如您所见,它占用每个元素,并尝试通过使用循环将元素前后的元素进行比较,从而尝试找到其位置

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

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