More Related Content
Similar to Insertion_Sort_Code.pdf (20)
Insertion_Sort_Code.pdf
- 1. ...es of C++Insertion_Sort_codeInsertion_Sort_code.cpp 1
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
// Insertion_Sort_code.cpp : This file contains the 'main' function.
Program execution begins and ends there.
//
#include < iostream >
using namespace std;
void insertionSort(int arr[])
{
int key;
int j = 0;
for (int i = 1; i < 5; i++)
{
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int myarray[5];
cout << "Enter 5 integers in any order" << endl;
for (int i = 0; i < 5; i++)
{
cout << "myarray[" << i << "] : ";
cin >> myarray[i];
}
cout << endl << endl;
cout << "Before Sorting: " << endl;
for (int i = 0; i < 5; i++)
{
cout << "myarray[" << i << "] : " << myarray[i] << endl;
}
insertionSort(myarray);
cout << endl << endl;
cout << endl << "After Sorting: " << endl;
for (int i = 0; i < 5; i++)
{
cout << "myarray[" << i << "] : "<< myarray[i] << endl;
}