Insertion Sort in c++

#include<iostream>
using namespace std;

void printArray (int *arr, int n);

class InsertionSort {
    public:
    void iSort(int *arr, int n) {
        int j,x;
        
        for(int i = 1; i<n; i++) {
            j = i-1;
            x = arr[i];
            
            while(j > -1 && arr[j] > x) {
                arr[j+1] = arr[j];
                j--;
            }
            arr[j+1] = x;
        }
    }
};

int main() {
    int arr[100];
    int n;
    
    cout<<"\t--- Insertion Sort ---\n";
    
    cout<<"enter size for array: ";
    cin>>n;
    
    cout<<"enter "<<n<<" elements: \n";
    for(int i = 0; i<n; i++){
        cout<<"enter element arr["<<i<<"]: ";
        cin>>arr[i];
    }
    
    cout<<"\n --- before sorting ---\n";
    printArray(arr,n);
    InsertionSort sort;
    sort.iSort(arr,n);
    
    cout<<"\n --- after sorting ---\n";
    printArray(arr,n);
}

void printArray (int *arr, int n) {
    for(int i = 0; i<n; i++){
        cout<<arr[i]<<"\t";
    }
}





Comments

Popular posts from this blog

AI and Human Evolution

To Do List App (GUI) using C#

Snake Game using JAVA