1.冒泡排序
时间复杂度 O ( n 2 ) O(n^2) O(n2),空间复杂度 O ( 1 ) O(1) O(1)。
a.比较相邻的元素。如果第一个比第二个大,就交换他们两个。
b.对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
c.针对所有的元素重复以上的步骤,除了最后一个。
d.持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
若为n个数,一共需遍历n-1次,每次讲最大的数放到最后一位。第i次需遍历前n-i+1个数。
#include<iostream>
#include<thread>
using std::cout;
using std::endl;
void swap(int &a, int &b) {
a = a + b;
b = a - b;
a = a - b;
}
void bubbleSort(int *unsortArray, const int &length) {
for (int i = 0; i < length; ++i) {
for (int j = 0; j < length - 1 - i; ++j) {
if (unsortArray[j] > unsortArray[j + 1]) {
swap(unsortArray[j], unsortArray[j + 1]);
}
}
}
}
int main() {
int sort[] = { 9,8,7,6,5,4,3,2,1,0 };
int length = sizeof(sort) / sizeof(int);
bubbleSort(sort, length);
for (int i = 0; i < length; ++i) {
cout << sort[i] << endl;
}
while (1) {
std::this_thread::sleep_for(std::chrono::microseconds(1000));
}
}
2.选择排序
时间复杂度为 O ( n 2 ) O(n^2) O(n2),空间复杂度 O ( 1 ) O(1) O(1)。
第1趟,在待排序记录r[1]r[n]中选出最小的记录,将它与r[1]交换;第2趟,在待排序记录r[2]r[n]中选出最小的记录,将它与r[2]交换;以此类推,第i趟在待排序记录r[i]~r[n]中选出最小的记录,将它与r[i]交换,使有序序列不断增长直到全部排序完毕。
#include<iostream>
#include<thread>
using std::cout;
using std::endl;
void swap(int &a, int &b) {
int tem = 0;
tem = a;
a = b;
b = tem;
}
void selectionSort(int *unsortArray, const int &length) {
int minIndex = -1;
for (int i = 0; i < length; ++i) {
minIndex = i;
for (int j = 0; j < length - i; ++j) {
if (unsortArray[j + i] < unsortArray[minIndex]) {
minIndex = j + i;
}
}
swap(unsortArray[i], unsortArray[minIndex]);
}
}
int main() {
int sort[] = { 9,8,7,6,5,4,3,2,1,0 };
int length = sizeof(sort) / sizeof(int);
selectionSort(sort, length);
for (int i = 0; i < length; ++i) {
cout << sort[i] << endl;
}
while (1) {
std::this_thread::sleep_for(std::chrono::microseconds(1000));
}
}
3.插入排序
时间复杂度 O ( n 2 ) O(n^2) O(n2),空间复杂度 O ( 1 ) O(1) O(1)。
通过扫描前面已排序的子列表,将位置i处的元素定位到从0到i的子列表之内的正确的位置上。
#include<iostream>
#include<thread>
using std::cout;
using std::endl;
void insertSort(int *unsortArray, const int &length) {
for (int i = 1; i < length; ++i) {
for (int j = 0; j < i + 1; ++j) {
if (unsortArray[j] > unsortArray[i]) {
int tem = unsortArray[i];
for (int k = 0; k < i - j; ++k) {
unsortArray[i - k] = unsortArray[i - k - 1];
}
unsortArray[j] = tem;
break;
}
}
}
}
int main() {
int sort[] = { 9,8,7,6,5,4,3,2,1,0 };
int length = sizeof(sort) / sizeof(int);
insertSort(sort, length);
for (int i = 0; i < length; ++i) {
cout << sort[i] << endl;
}
while (1) {
std::this_thread::sleep_for(std::chrono::microseconds(1000));
}
}
4.归并排序
时间复杂度 O ( N ∗ l o g N ) O(N*logN) O(N∗logN),空间复杂度为 O ( N ) O(N) O(N)。
先将所有数两个一组排序,再将两组四个数一起排序为新的一组,循环下去每次合并两组,直到所有数有序。
递归法:
#include<iostream>
#include<