fork download
  1. #include<iostream>
  2. #include <ctime>
  3. using namespace std;
  4.  
  5. void Insertion_sort(int arr[], int n){
  6. int i,j, key;
  7. for(i=1; i<n;i++){
  8. key = arr[i];
  9. j=i-1;
  10. while(j>=0 && arr[j]>key){
  11. arr[j+1] = arr[j];
  12. j--;
  13. }
  14. arr[j+1]=key;
  15. }
  16. }
  17.  
  18. int main()
  19. {
  20. int n,i;
  21. cout<<"Enter the size of an array: ";
  22. cin>>n;
  23. int arr[n];
  24. cout<<"Enter the elements: ";
  25. for(i=0; i<n; i++)
  26. {
  27. cin>>arr[i];
  28. }
  29. clock_t start = clock();
  30. Insertion_sort(arr,n);
  31. clock_t end = clock();
  32. cout << "Sorted array: ";
  33. for(i=0; i<n; i++)
  34. {
  35. cout<<arr[i]<<" ";
  36. }
  37. double time_taken = double(end - start) / CLOCKS_PER_SEC * 1000;
  38. cout<< endl<< "Time taken to sort the array: " << time_taken << " ms" << endl;
  39. return 0;
  40. }
  41.  
  42.  
Success #stdin #stdout 0s 5288KB
stdin
5
1 2 3 4 5
stdout
Enter the size of an array: Enter the elements: Sorted array: 1 2 3 4 5 
Time taken to sort the array: 0 ms