sort algorithm

Bubble Sort

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
void (int *a, int len) {
for (int i = 1; i < len; i++) {
for (int j = 0;j < len - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}


void bubble_sort_op(int *a, int len) {
for (int i = 1; i < len; i++) {
int flag = 0;
for (int j = 0; j < len - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
flag = 1;
}
}
if (flag == 0) {
break;
}
}
}

Insertion Sort

1
2
3
4
5
6
7
8
9
10
11
void insertion_sort(int *a, int len) {
for (int i = 1; i < len; i++) {
int temp = a[i];
int j = i - 1;
while (j >= 0 && a[j] > temp) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}
}

Quick Sort

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

void quick_sort(int* a, int l, int r) {
int pivot = a[l];
int left = l, right = r;
if (l >= r) {
return;
}
while (left < right) {

while (left < right && (a[right] >= pivot)) {
right--;
}
a[left] = a[right];
while (left < right && (a[left] <= pivot)) {
left++;
}
a[right] = a[left];


}
a[left] = pivot;

quick_sort(a, l, left - 1);
quick_sort(a, left + 1, r);

}