直接插入算法,每次将未排序的第一个元素插入到前半部分以及排好序的元素中。关键是要在已排好的部分进行移位操作。
//直接插入排序算法 void InsertSort(int a[],int n) { for (int i = 1; i < n; i++) { if (a[i] < a[i - 1]) { int j = i - 1; int tmp = a[i]; while (tmp < a[j]) { a[j + 1] = a[j]; j--; } a[j + 1] = tmp; } } }
冒泡算法,最简单就是不加入标识符的,进行n-1次外循环,加入标识符后,有可能经过前几次后就已经有序了,此时就可以跳出外循环了。
//冒泡算法,没有改进的 void BubbleSort1(int a[],int n) { for (int i = 0; i < n-1; i++) { for (int j = i ; j < n-1; j++) { if (a[j + 1] < a[j]) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } } //冒泡算法,加入交换标志符 void BubbleSort2(int a[], int n) { for (int limit = n - 1; limit > 0; limit--) { bool flag = false; for (int j = 0; j < limit; j++) { if (a[j + 1] < a[j]) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; flag = true; } } if (!flag) break; } }
选择排序算法,每次从剩下的未排序的部分挑选出最小值,和第一个元素交换位置。
//选择排序法 void SelectSort(int a[], int n) { for (int i = 0; i < n - 1; i++) { int key,tmp; key=i; for (int j = i+1; j < n-1; j++) { if (a[j] <a[key]) { key= j; } } if (key != i) { tmp = a[key]; a[i] = a[key]; a[key] = tmp; } } }
希尔排序。希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量的逐渐减少,每组包含的关键词越来越多,当增量减少1时,元素被封为1组,算法变终止。
//希尔排序法 //辅助函数,子序列直接插入排序法 void ShellInsertSort(int a[], int n, int gap) { for (int i = gap; i < n; i++) { if (a[i] < a[i - gap]) { int j = i - gap; int tmp = a[i]; while (tmp < a[j]) { a[j + gap] = a[j]; j -= gap; } a[j + gap] = tmp; } } } void ShellSort(int a[], int n) { int gap = n / 2; while (gap >= 1) { ShellInsertSort(a, n, gap); gap = gap / 2; } }
快速排序算法。快速排序算法的思想是,先选一个“标尺”, 用它把整个队列过一遍筛子, 以保证其左边的元素都不大于它,其右边的元素都不小于它。这样,排序问题就被分割为两个子区间。 再分别对子区间排序就可以了。
//快速排序法 //辅助函数1:交换元素 void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; } //辅助函数2:找到数组的分给点 int Partition(int a[], int low, int high) { int privotkey = a[low]; while (low < high) { while (low<high && a[high]>privotkey) --high; swap(&a[low], &a[high]); while (low < high && a[low] < privotkey) ++low; swap(&a[low], &a[high]); } return low; } void QuickSort(int a[], int low, int high) { if (low < high) { int privot = Partition(a, low, high); QuickSort(a, low, privot - 1); QuickSort(a, privot + 1, high); } }验证
#include "stdafx.h" #include<stdio.h> using namespace std; //各种排序算法 int main() { int a[10] = { 0, 2, 1, 4, 5, 3, 6 ,7, 8, 9 }; //ShellSort(a, 10); QuickSort(a, 0, 9); for (int j = 0; j < 10; j++) { printf("%d\t", a[j]); } printf("\n"); return 0; }