-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
54 lines (50 loc) · 1.15 KB
/
Copy pathmain.cpp
File metadata and controls
54 lines (50 loc) · 1.15 KB
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
#include <iostream>
using namespace std;
/*!
* \brief insertionSort Sorts an array using the insertion sort algorithm
* \param arr Arry of integers to sort
* \param n Length of the array
*/
void insertionSort(int* arr, int n);
void printArray(int* arr, int n);
int main()
{
int arr[12] = {12, 2, 54, 1, 3, 4, 16, 13, 10, 24, 22, 30};
printArray(arr, 12);
insertionSort(arr, 12);
printArray(arr, 12);
return 0;
}
void insertionSort(int *arr, int n)
{
//Iterate starting from the second element
for (int i = 1; i < n; i++)
{
//Insertion range: 0 -> i-1
int j = i - 1;
int tmp = arr[i];
while (j >= 0)
{
if (arr[j] > tmp)
{
//move jth element to right
arr[j + 1] = arr[j];
}
else break;
j--;
}
//j now points to the element smaller than ith element
//insert ith element at index j + 1
arr[j + 1] = tmp;
}
}
void printArray(int *arr, int n)
{
for (int i = 0; i < n; i++)
{
if (i)
cout << ", ";
cout << arr[i];
}
cout << endl;
}