C++实现算法有冒泡排序/选择排序/插入排序/快排。ios
一只泡泡咕嘟咕嘟……c++
void bubbleSort(int* arr, int len) { for (int i = 0; i < len; i++) { for (int j = 0; j < len - i-1; j++) { if (arr[j] > arr[j + 1]) swap(arr[j], arr[j + 1]); } } }
矮子里面拔高个……web
void selectSort(int* arr, int len) { for (int i = 0; i < len; i++) { int minx = arr[i]; for (int j = i; j < len; j++) { if (arr[j] < arr[i]) { swap(arr[i], arr[j]); } } } }
你们给新来的挪挪窝……算法
void insertSort(int* arr, int len) { for (int i = 0; i < len - 1; i++) { int pre = i; int reg = arr[pre+1]; while (pre >= 0 && reg < arr[pre]) { arr[pre + 1] = arr[pre]; pre--; } arr[pre+1] = reg; } }
一只门槛(pivot)跳来跳去……svg
// How to partition; int partition(int* arr, int stt, int end) { int pivot = (stt + end) / 2; while (stt < end) { while (arr[stt] < arr[pivot] && stt<end) stt++; if (arr[stt] >= arr[pivot]) { swap(arr[stt], arr[pivot]); pivot = stt; } while (arr[end] > arr[pivot] && (stt < end)) end--; if (arr[end] <= arr[pivot]) { swap(arr[end], arr[pivot]); pivot = end; } } return pivot; } void quickSort(int* arr, int stt, int end) { if (stt >= end) return; int pivot = partition(arr, stt, end); quickSort(arr, stt, pivot); showArr(arr, 5); quickSort(arr, pivot+1, end); }
#include <stdlib.h> #include <iostream> #include <algorithm> using namespace std; void showArr(int* arr, int len) { for (int i = 0; i < len; i++) { cout << arr[i] << ' '; }printf("\n"); } int main() { int arr[5] = { 5, 2, 3, 11, 7 }; //bubbleSort(arr, 5); //selectSort(arr, 5); //insertSort(arr, 5); quickSort(arr, 0, 4); showArr(arr, 5); system("PAUSE"); return 0; }