-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion_sort.cc
More file actions
50 lines (41 loc) · 850 Bytes
/
insertion_sort.cc
File metadata and controls
50 lines (41 loc) · 850 Bytes
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
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
static const int LEN = 6;
void swap(int& a, int& b)
{
int tmp = a;
a = b;
b = tmp;
}
void output(int arr[], int length)
{
cout << arr[0];
for(int i=1; i<length; ++i)
cout << " " << arr[i];
cout << endl;
}
void insertionSort(int arr[], int length)
{
int i, j;
for(i = 1; i <length; i++)
{
j = i; // Element unsorted
while(j > 0 && arr[j-1] > arr[j]) {
swap(arr[j-1], arr[j]);
j--;
}
cout << "Loop one fin with i = " << i << ", looking at " << arr[j] << endl;
output(arr, length);
}
}
int main()
{
cout << "Before: ";
int vec[] = { 7, -5, 2, 16, 4, 3};
output(vec, LEN);
insertionSort(vec, LEN);
return 0;
}