Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,988 questions

51,933 answers

573 users

How to implement insertion sort in C++

1 Answer

0 votes
#include <iostream>
#include <ctime>

#define SIZE 6

void print_array(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }
}
 
void insertion_sort(int arr[], int size) {
    int j, tmp;
      
    for (int i = 1 ; i < size; i++) { 
        j = i;
       
        while (j > 0 && arr[j] < arr[j - 1]) {
            tmp = arr[j];
            arr[j] = arr[j - 1];
            arr[j - 1] = tmp;
            j--;
        }
    }
}
  
 
int main(void)
{
    int arr[SIZE], i;
    int size = sizeof(arr) / sizeof(arr[0]);
   
    srand(time(NULL));
     
    for (i = 0; i < size; i++) {
         arr[i] = rand() % 100 + 1;
    }
     
    print_array(arr, size);
     
    std::cout << "\n";
      
    insertion_sort(arr, size);
      
    std::cout << "\nafter insertion_sort:\n\n";
    print_array(arr, size);
}
  
 
 
  
/*
run:
  
4 20 92 57 64 71 

after insertion_sort:

4 20 57 64 71 92 
 
*/

 



answered Feb 23, 2024 by avibootz
edited Feb 23, 2024 by avibootz

Related questions

1 answer 187 views
187 views asked Sep 14, 2014 by avibootz
2 answers 138 views
1 answer 141 views
141 views asked Jun 1, 2019 by avibootz
1 answer 80 views
3 answers 195 views
...