Implement Insertion Sort in DAA

Implement Insertion Sort in DAA 

Program :-

  1. #include<iostream>
  2. using namespace std;
  3. void display(int *array, int size){
  4.    for(int i = 0; i<size; i++)
  5.       cout << array[i] << " ";
  6.    cout << endl;
  7. }
  8. void insertionSort(int *array, int size){
  9.    int key, j;
  10.    for(int i = 1; i<size; i++) {
  11.       key = array[i];
  12.       j = i;
  13.       while(j > 0 && array[j-1]>key){
  14.          array[j] = array[j-1];
  15.          j--;
  16.       }
  17.       array[j] = key;
  18.    }
  19. }
  20. int main(){
  21.    int n;
  22.    cout << "Enter the number of elements: ";
  23.    cin >> n;
  24.    int arr[n];
  25.    cout << "Enter elements:" << endl;
  26.    for(int i = 0; i<n; i++){
  27.       cin >> arr[i];
  28.    }
  29.    cout << "Array before Sorting: ";
  30.    display(arr, n);
  31.    insertionSort(arr, n);
  32.    cout << "Array after Sorting: ";
  33.    display(arr, n);
  34. }


Comments