-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertion.h
55 lines (49 loc) · 1.44 KB
/
insertion.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// =================================================================
//
// File: insertion.h
// Author: Pedro Perez
// Description: This file contains the implementation of the
// insertion sort.
//
// Copyright (c) 2020 by Tecnologico de Monterrey.
// All Rights Reserved. May be reproduced for any non-commercial
// purpose.
// =================================================================
#ifndef INSERTION_H
#define INSERTION_H
#include "header.h"
#include <vector>
// =================================================================
// Performs the insertion sort algorith on an array.
//
// @param A, an array of T elements.
// @param size, the number of elements in the array.
// =================================================================
template <class T>
int insertionSort(T *arr, int size) {
int counter = 0;
for(int i = 1; i < size; i++){
for(int j = i; j > 0 && arr[j] < arr[j - 1]; j--){
swap(arr, j, j - 1);
counter++;
}
}
return counter;
}
// =================================================================
// Performs the insertion sort algorith on a vector.
//
// @param A, a vector of T elements.
// =================================================================
template <class T>
int insertionSort(std::vector<T> &v) {
int xounter = 0;
for(int i = 1; i < v.size(); i++){
for(int j = i; j > 0 && v[j] < v[j - 1]; j--){
xounter+=1;
swap(v, j, j - 1);
}
}
return xounter;
}
#endif /* INSERTION_H */