- 常用排序算法:冒泡 选择 直接插入 二分插入 希尔排序 快速排序 归并排序 堆排序
算法的时间复杂度和空间复杂度就不分析了,自行百度,代码如下:
#include<iostream>
#include<string>
using namespace std;
void bubble_sort1(int arr[], int len){
for(int i = 0; i < len-1; i++){
for(int j = len-1; j > i; j--){
if(arr[j] < arr[j-1]){
int tmp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = tmp;
}
}
}
}
void bubble_sort2(int arr[], int len){
for(int i = len-1; i > 0; i--){
for(int j = 0; j < i; j++){
if(arr[j] > arr[j+1]){
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
}
void selectSort(int arr[], int len){
for(int i = 0; i < len-1; i++){
int index = i;
for(int j = i+1; j < len; j++){
if(arr[j] < arr[index])
index = j;
}
if(index != i){
int tmp = arr[i];
arr[i] = arr[index];
arr[index] = tmp;
}
}
}
void insert_sort(int arr[], int len){
for(int i = 1; i < len; i++){
int key = arr[i];
int j = i-1;
while(j >= 0 && arr[j] > key){
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
}
int binarySearch(int start, int end, int arr[], int target){
while(start < end){
int mid = (start+end)/2;
if(arr[mid] < target)
start = mid+1;
else
end = mid-1;
}
return start;
}
void binary_sort(int arr[], int len){
for(int i = 1; i < len; i++){
int key = arr[i];
if(arr[i-1] > key){
int index = binarySearch(0, i-1, arr, key);
for(int j = i; j > index; j--)
arr[j] = arr[j-1];
arr[index] = key;
}
}
}
void shellSort1(int arr[], int len){
for(int gap = len/2; gap > 0; gap /= 2){
for(int i = 0; i < gap; i++){
for(int j = i+gap; j < len; j += gap){
if(arr[j] < arr[j-gap]){
int key = arr[j];
int k = j-gap;
while(k >= 0 && arr[k] > key){
arr[k+gap] = arr[k];
k -= gap;
}
arr[k+gap] = key;
}
}
}
}
}
void shellSort2(int arr[], int len){
for(int gap = len/2; gap > 0; gap /= 2){
for(int j = gap; j < len; j++){
if(arr[j] < arr[j-gap]){
int tmp = arr[j];
int k = j - gap;
while(k >= 0 && arr[k] > tmp){
arr[k+gap] = arr[k];
k -= gap;
}
arr[k+gap] = tmp;
}
}
}
}
void quick_sort(int arr[], int left, int right){
if(left < right){
int i = left, j = right, target = arr[left];
while(i < j){
while(i < j && arr[j] > target){
j--;
}
if(i < j) arr[i++] = arr[j];
while(i < j && arr[i] < target)
i++;
if(i < j) arr[j--] = arr[i];
}
arr[i] = target;
quick_sort(arr, left, i-1);
quick_sort(arr, i+1, right);
}
}
void merge(int arr[], int tmpArr[], int start, int mid, int end){
int i = start, j = mid+1;
int k = 0;
while(i <= mid && j <= end){
if(arr[i] > arr[j])
tmpArr[k++] = arr[j++];
else
tmpArr[k++] = arr[i++];
}
while(i <= mid){
tmpArr[k++] = arr[i++];
}
while(j <= end){
tmpArr[k++] = arr[j++];
}
for(i = 0; i < k; i++){
arr[start+i] = tmpArr[i];
}
}
void mergeSort(int arr[], int start, int end, int tmpArr[]){
if(start < end){
int mid = (start+end)/2;
mergeSort(arr, start, mid, tmpArr);
mergeSort(arr, mid+1, end, tmpArr);
merge(arr, tmpArr, start, mid, end);
}
}
int main(){
int arr[] = {2,4,3,2,6,7};
int tmpArr[6];
mergeSort(arr, 0, 5, tmpArr);
for(int i = 0; i < 6; i++) cout << arr[i] << endl;
}
- 快速排序算法有很多优化方式,比如随机选取基准点,对区间比较小的不使用快速排序,以免递归深度过深。