Posted on 

sort algorithms

学习一下几个基本的排序算法,记录供日后参考。

插入排序:

1
2
3
4
5
6
7
8
void insert_sort(int nums[], int len){
for (int i = 1, j = 0; i < len; ++i) {
int temp = nums[i];
for (j = i - 1; j >= 0 && nums[j] > temp; --j)
nums[j+1] = nums[j];
nums[j+1] = temp;
}
}

冒泡排序

1
2
3
4
5
6
7
8
void bsort(int nums[], int len){
for (int i = 0; i < len-1; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (nums[j] > nums[j+1])
swap(nums[j], nums[j+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
#include <iostream>
using namespace std;

int partition(int nums[], int low, int high)
{
int p = nums[high];
int i = low - 1;
for (int j = low; j <= high - 1; j++) {
if (nums[j] < p) {
i++;
swap(nums[i], nums[j]);
}
}
swap(nums[i+1], nums[high]);
return i + 1;
}

void qsort(int nums[], int low, int high)
{
if (low < high) {
int i = partition(nums, low, high);
qsort(nums, low, i-1);
qsort(nums, i+1, high);
}
}



void debug(int nums[], int last) {
for (int i = 0; i <= last; i++) {
printf("%d ", nums[i]);
}
printf("\n");
}

int main() {
int a[] = {1, 3, 2, 3, 4, 1, 2, 6, 5, 9, 6};
int size = sizeof(a)/sizeof(int);
qsort(a, 0, size-1);
debug(a, size-1);
}