-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsorting.c
More file actions
43 lines (38 loc) · 1.01 KB
/
sorting.c
File metadata and controls
43 lines (38 loc) · 1.01 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
#include <stdio.h>
//shifts i elements from the start of arr to the right.
void shift_element(int* arr, int i) {
int *arrStart = arr;
int *fromArrPtr = arrStart+i-1;
int *shiftToPtr = fromArrPtr+1;
for (int j=0; j<i; j++) {
*shiftToPtr-- = *fromArrPtr--;
}
}
//sorts an array with len elements using insertion sort algorithm
void insertion_sort(int* arr , int len) {
int *arrStart = arr;
for (int i=1; i<len; i++) {
int *iPtr = arrStart+i;
for (int j=0; j<i; j++) {
int *jPtr = arrStart+j;
if (*iPtr<*jPtr) {
int temp = *iPtr;
shift_element(jPtr, i-j);
*jPtr = temp;
break;
}
}
}
/*
for (int i=1; i<len; i++) {
for (int j=0; j<i; j++) {
if (arr[i]<arr[j]) {
int temp = arr[i];
shift_element(&arr[j], i-j);
arr[j] = temp;
break;
}
}
}
*/
}