我的插入排序代码有问题

There's something wrong with my Insertion Sort code

本文关键字:有问题 代码 插入排序 我的      更新时间:2023-10-16

我从mycodeschool那里学到了这种实现,方法对我来说似乎还可以,因为那是那里的讲师的教学方式,我做了相同的实现,但我的代码以某种方式给出了一个问题,也请只需忽略时间函数,因为错误在其他地方。我删除了它,错误仍然相同。

 //insertion sort
    #include<iostream>
    #include <ctime>
    using namespace std;
    class insertion{
    public:
        insertion(){} //constructor
        void sort(int a[], int n) { //insertion sort function
            for (int i = 1; i < n; i++) {
                int value = a[i];
                int index = i;
                while (i > 0 && a[i - 1] > value) {
                    a[index] = a[index - 1];
                    index=index-1;
                }
                a[index] = value;
            }
        }
        //display function
        void display(int a[], int n) {
            for (int i = 0; i < n; i++) {
                cout << a[i] << endl;
            }
        }
    };
    void main(){
        insertion ins;
        int a[10];
        int n = 10;
        cout << "Enter the elements:" << endl;
        for (int i = 0; i < n; i++) {
            cin >> a[i];
        }
        unsigned int start = clock(); //measuring time of sort from here
        cout << "waiting for keyhit";
        cin.ignore();
        ins.sort(a, n);
        ins.display(a, n);
        cout << "Time taken in millisecs: " << clock() - start; //to here
        cin.ignore();
    }

我可以看到的一个错误是您在循环的终止状态下对i的使用不正确。您应该使用变量索引,我认为这也是您的最初意图。

我描述了校正后,您可能会在此处观察到的正如其他主()所观察到的那样,您的排序功能似乎有效。下面,您可能会在校正之后看到排序函数的定义

void sort(int a[], int n) { //insertion sort function
    for (int i = 1; i < n; i++) {
        int value = a[i];
        int index = i;
        while (index > 0 && a[index - 1] > value) {
            a[index] = a[index - 1];
            index=index-1;
        }
        a[index] = value;
    }
}