简体   繁体   中英

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

OUTPUT1

Output 2

OUTPUT2

Output 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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