-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertSort.cpp
More file actions
54 lines (44 loc) · 875 Bytes
/
InsertSort.cpp
File metadata and controls
54 lines (44 loc) · 875 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
51
52
53
54
//Insert Sort
//in iteration i, swap a[i] with each larger to its left.
//time: O(n^2) compares, O(n^2) exchanges
//it's good if the array is partilly sorted
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define SORT_NUM 20
void swap(int *a,int m,int n)
{
int tmp = a[m];
a[m] = a[n];
a[n] = tmp;
}
void display(int *a,int num)
{
for(int i=0;i<num;i++)
cout << "sorted array [" << i << "] = " << a[i] << endl;
}
void InsertSort(int *a,int num)
{
for(int i=0;i<num;i++)
{
for(int j=i;j>0;j--)
{
if(a[j]<a[j-1])
swap(a,j,j-1);
else
break;
}
}
}
int main()
{
int num = SORT_NUM;
int a[num]= {0};
srand((int)time(0));
for(int i=0;i<num;i++)
a[i] = rand()%100;
InsertSort(a,num);
display(a,num);
return 0;
}