C++常用的排序算法:
冒泡排序
void BubbleSort(int *a,int len)
{
int temp;
for(int i=0; i<len; ++i){
for(int j=0; j<len-i-1; ++j){
if(a[j]>a[j+1]){
temp =a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
选择排序
void SelectSort(int *a,int len)
{
for(int i=0; i<len; ++i){
int m_index = i;
for(int j=i+1; j<len; ++j){
if(a[j] < a[m_index]){
m_index = j;
}
}
int temp = a[m_index];
a[m_index] = a[i];
a[i] = temp;
}
插入排序
void InsertSort(int *a,int len)
{
for(int i=0; i<len; ++i){
for(int j=i; j>0; --j){
if(a[j]<a[j-1]){
int temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
}
希尔排序
int shell_sort(int *data, int length) {
int gap = 0;
int i = 0, j = 0;
int temp;
for (gap = length / 2;gap >= 1; gap /= 2) { //分组
for (i = gap;i < length;i ++) {
temp = data[i];
for (j = i-gap;j >= 0 && temp < data[j];j = j - gap) {
data[j+gap] = data[j];
}
data[j+gap] = temp;
}
}
return 0;
}
归并排序
void merge(int *data, int *temp, int start, int middle, int end) { //后合并
int i = start, j = middle+1, k = start;
while (i <= middle && j <= end) {
if (data[i] > data[j]) {
temp[k++] = data[j++];
} else {
temp[k++] = data[i++];
}
}
while (i <= middle) {
temp[k++] = data[i++];
}
while (j <= end) {
temp[k++] = data[j++];
}
for (i = start;i <= end;i ++) {
data[i] = temp[i];
}
}
int merge_sort(int *data, int *temp, int start, int end) { //先分
int middle;
if (start < end) {
middle = start + (end - start) / 2;
merge_sort(data, temp, start, middle);
merge_sort(data, temp, middle+1, end);
merge(data, temp, start, middle, end);
}
}
快排
void sort(int *data, int left, int right) {
if (left >= right) return ;
int i = left;
int j = right;
int key = data[left];
while (i < j) {
while (i < j && key <= data[j]) {
j --;
}
data[i] = data[j];
while (i < j && key >= data[i]) {
i ++;
}
data[j] = data[i];
}
data[i] = key;
sort(data, left, i - 1);
sort(data, i + 1, right);
}
在一个字符串中,查找匹配子串,常用的KMP算法
void make_next(const char *pattern, int *next) {
int q, k;
int m = strlen(pattern);
next[0] = 0;
for (q = 1,k = 0;q < m; q ++) {
while (k > 0 && pattern[q] != pattern[k])
k = next[k-1];
if (pattern[q] == pattern[k]) {
k ++;
}
next[q] = k;
}
// 假设 pattern = "abcabd"
// next[0] = 0;
// q=1, k=0, pattern[q]:pattern[k] = b:a, next[1] = 0;
// q=2, k=0, pattern[q]:pattern[k] = c:a, next[2] = 0;
// q=3, k=0, pattern[q]:pattern[k] = a:a, k++, next[3] = 1;
// q=4, k=1, pattern[q]:pattern[k] = b:b, k++, next[4] = 2;
// q=5, k=2, pattern[q]:pattern[k] = c:c, k++, next[5] = 3;
// q=6, k=3, pattern[q]:pattern[k] = d:a, k=next[k-1] -> k=0; next[6] = 0;
}
int kmp(const char *text, const char *pattern, int *next) {
int n = strlen(text);
int m = strlen(pattern);
make_next(pattern, next);
int i, q;
for (i = 0, q = 0;i < n;i ++) {
while (q > 0 && pattern[q] != text[i]) {
q = next[q-1];
}
if (pattern[q] == text[i]) {
q ++;
}
if (q == m) {
//printf("Pattern occurs with shift: %d\n", (i-m+1));
break;
}
}
return i-q+1;
}