summaryrefslogtreecommitdiff
path: root/c/dataStructure/sorting/insertSort.c
blob: 741f2956898ccf25db0fd55e4500c4b88fb35b21 (plain)
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
56
57
58
59
60
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

#define SIZE 10

void swap(int * a, int * b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}

void generateRandom(int * arr, int n)
{
	time_t sr;
	srand(*&sr);

	for(int i = 0; i < n; i++)
		arr[i] = rand() % 100;
}

void print(int * arr, int n)
{
	for(int i = 0; i < n; i++)
		printf("%3d",*(arr+i));
	putchar('\n');
}

void insertSort(int * arr, int n)
{
	int key, i, j;
	
	for (i = 1; i < n; i++)
	{
		key = arr[i];
		j = i - 1;

		while (j >= 0 && key < arr[j])
		{
			arr[j+1] = arr[j];
			j--;
		}
		arr[j+1] = key;
	}
}

int main(void)
{
	int arr[SIZE];
	generateRandom(arr,SIZE);

	print(arr,SIZE);

	insertSort(arr,SIZE);

	print(arr,SIZE);

	return 0;
}