基础排序算法:冒泡法,选择法,直接插入法,归并排序法

来源:互联网 发布:matlab socket编程实例 编辑:程序博客网 时间:2024/06/07 05:10

冒泡排序:

/* * 冒泡法: * 每次将相邻数中的较小值排到较大值的前面 * 直到无需再交换为止 * */#include <iostream>using namespace std;template<typename T>inline void bubbleSort(T arr[], size_t len){T temp;for (size_t i = 0; i < len-1; i++) {for (size_t j = len-1; j > i; j--) {if (arr[j-1] > arr[j]) { //逐次将相邻数的较小值和较大值间进行交换//使最小值被交换到最前面temp = arr[j-1];arr[j-1] = arr[j];arr[j] = temp;}}}for (size_t i = 0; i < len; i++)cout << arr[i] << " ";}int main(int argc, char **argv){int array[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};size_t len = sizeof(array)/sizeof(*array);bubbleSort(array, len);return 0;}

选择排序:

/* * 选择排序: * 每次遍历数组,找出未排序部分的最小值 * 将其继续排到已排好序部分的后面 * */template<typename T>inline void selectionSort(T arr[], int len){T temp;int min;for (int i = 0; i < len - 1; i++) {min = i; //当前的最小值下标(未排序状态)for (int j = i + 1; j < len; j++) {if (arr[min] > arr[j])min = j;//遍历未排序部分的元素,找到最小值的小标}if (min != i) { //把已找到的目前最小值排到已排好序的数组后面temp = arr[min];arr[min] = arr[i];arr[i] = temp;}}for (int n = 0; n < len; n++)cout << arr[n] << " ";}

直接插入法:

/* * 插入排序: * 从左到右遍历数组,将每个元素插入到合适的位置 * */void insertionSort(int arr[], int len){int i, j, key;for (i = 1; i < len; i++) {key = arr[i];//从数组的0下标开始找到第一个比arr[i]大的数arr[j]//将a[i]~a[j]之间的全部元素后移,然后将arr[i]放到原arr[j]的位置for (j = i-1; j >= 0 && arr[j] > key; j--) {arr[j+1] = arr[j];}arr[j+1] = key;}for (int i = 0; i < len; i++)cout << arr[i] << " ";}

归并排序1(递归版本):

#include <iostream>using namespace std;/* * 排序需要原数组,同时还需要借助一个数组 * */void merge(int arr[], int start, int mid, int end, int temp[])//把已排好序的两小部分拼接起来{int i = start, j = mid+1, k = 0;while (i <= mid && j <= end) {if (arr[i] > arr[j])temp[k++] = arr[j++];else temp[k++] = arr[i++];}while (i <= mid)temp[k++] = arr[i++];while (j <= end)temp[k++] = arr[j++];for (int n = 0; n < k; n++)arr[start+n] = temp[n];}void merge_sort(int arr[], int start, int end, int temp[])//排序还需要知道每段排序部分的开始和结束{if (start >= end) return;//把原数组再折半分别排序int mid = (start + end)/2; merge_sort(arr, start, mid, temp);merge_sort(arr, mid+1, end, temp);merge(arr, start, mid, end, temp);}void sort(int arr[], int len){int *temp = new int[len];merge_sort(arr, 0, len-1, temp);delete[] temp;}int main(int argc, char **argv){int array[] = {9,7,5,3,4,1,0};sort(array, sizeof(array)/sizeof(*array));for (auto x : array)cout << x;return 0;}


归并排序2(C++的qsort()函数):

#include <iostream>using namespace std;//compare 函数int compare(const void *a, const void *b){int *p1 = (int *)a;int *p2 = (int *)b;return *p1 > *p2;}int main(int argc, char** argv){int array[] = {1, 8 , 3, 4, 2, 9, 6, 5, 0};//sort(array, sizeof(array)/sizeof(*array));qsort(array, sizeof(array)/sizeof(*array), sizeof(*array), compare);for (auto i : array)cout << i;return 0;}








0 0