插入排序
#include <iostream>
using namespace std;
template<class T>
void insertionSort(T a[], int n) {
int i, j;
T temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i;
while (j > 0 && temp < a[j-1]) {
//从第二个数开始比较,只要比前一个数小,前一个数往后移一格。
//移动完毕后,把比较的数temp放到当前空位中
a[j] = a[j - 1];
j--;
}
a[j] = temp;
}
}
int main()
{
int a[] = { 3, 51, 22, 4434, 6, 433, 56466, 2 };
insertionSort(a, 7);
for (int i = 0; i < 8; i++) {
cout << a[i] << " ";
}
return 0;
}
选择排序
#include<iostream>
using namespace std;
template<class T>
void swap1(T &x, T &y) {
T temp = x;
x = y;
y = temp;
}
template<class T>
void selectsort(T a[], int n) {
//选择排序类似于冒泡排序
//选择排序确定最小值的下标后进行一次交换
//冒泡排序每次发现更小的数,都会进行一次交换
//选择排序只适用于数组
for (int i = 0; i < n - 1; i++) {
int leastindex = i;
for (int j = i + 1; j < n; j++)
if (a[j] < a[leastindex])
leastindex = j;
swap1(a[i], a[leastindex]);
}
}
int main() {
int a[] = { 23, 4, 5345, 22, 567, 2, 6, 88, 96, 67 };
selectsort(a, 10);
for (int i = 0; i < 10; i++) {
cout << a[i] << " ";
}
return 0;
}
冒泡排序
1.如果某一轮没有发生过交换,说明数组已经有序,那么以后也不会发生交换,此时可以终止迭代
2.记录每一次最后发生交换的位置,下一轮只需要扫描到此位置的前一个即可,下一轮只用判断a2和a3即可。
这种算法比较巧妙,通过把最后交换位置lastexchangeindex复制给i,用while来控制循环,无需break
#include <iostream>
using namespace std;
template<class T>
void myswap(T& x, T& y) {
T temp = x;
x = y;
y = temp;
}
template<class T>
void bubblesort(T a[], int n) {
int i = n - 1;
while (i > 0) {
int lastexchangeindex = 0; // 很巧妙,每轮循环都要让其为0,如果没发生交换,i也为0,跳出循环
for (int j = 0; j < i; j++) {
if (a[j + 1] < a[j]) {
myswap(a[j + 1], a[j]);
lastexchangeindex = j;
}
}
i = lastexchangeindex; //记录最后交换的位置
}
}
int main()
{
int a[] = { 9, 8, 7, 6, 22, 33, 11, 2, 1, 3, 5 };
bubblesort(a, 10);
for (int i = 0; i < 10; i++) {
cout << a[i] << " ";
}
return 0;
}
小K的冒泡算法
template<class T>
void bubblesort(T a[], int n) {
int LastExchangeIndex = n - 1;
int position = 0;//要初始化为0,防止本身次序是对的
for(int i = 0; i < n - 1; i++) {
bool noexchange = true; //通过布尔量来确认是不是这一轮进行了交换
for (int j = 0; j < LastExchangeIndex; j++) {
if (a[j + 1] < a[j]) {
myswap(a[j + 1], a[j]);
position = j; //每轮交换后,position记录了最终位置
noexchange = false;
}
}
LastExchangeIndex = position; //记录最终交换位置
if (noexchange) //如果这一轮没有进行任何位置调整,后续不用再进行
break;
}
}
二分法查找
template<class T>
int binsearch(T a[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2; //注意要在循环内部更新mid
if (a[mid] == key)
return mid;
else if (a[mid] > key)
high = mid - 1;
else
low = mid + 1;
}
return -1;
}