Insertion Sort Using C++

Link Copied To Clipboard !

insertion-sort-in-cpp Algorithms

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.

Insertion Sort Using C++



#include<iostream>
using namespace std;

class List{
    private:
        int* arr;
        int len;

    public:
        List(){
            this->arr = NULL;
            this->len = 0;
        }

        void populate(){
            do{
                cout<<"enter the size:"<<endl;
                cin>>this->len;
            }while(this->len < 0);

            this->arr = new int[this->len];

            for(int i = 0; i < this->len; i++){
                cout<<"enter "<<i<<"th item"<<endl;
                cin>>*(arr+i);
            }
        }

        void insertionSort(){
            if(arr == NULL){
                cout<<"list is empty !"<<endl;
                return;
            }
            if(this->len == 1) return;
            int temp, j;
            for(int i = 1; i < this->len; i++){
                temp = *(arr + i);
                j = i - 1;
                while(j >= 0 && *(arr + j) > temp){
                    *(arr + j + 1) = *(arr + j);
                    j--;
                }
                *(arr + j + 1) = temp;
            }
        }

        int length(){
            return len;
        }

        void display(){
            if(arr == NULL){
                cout<<"list is empty !"<<endl;
                return;
            }
            cout<<"[";
            for(int i = 0; i < this->len; i++){
                if(i != len-1){
                    cout<<*(arr+i)<<", ";
                }else{
                    cout<<*(arr+i);
                }
            }
            cout<<"]"<<endl;
        }

        ~List(){
            delete arr;
        }
};

int main(){
    List list;
    list.populate();
    cout<<"unsorted list:";
    list.display();
    cout<<"sorted list:";
    list.insertionSort();
    list.display();
    return 0;
}


You May Also Like