八大排序算法

冒泡排序

void bubble_sort(vector<int> &nums){
    for (int i = 0; i < nums.size() - 1; i++) { // times
        for (int j = 0; j< nums.size() - i- 1; j++) { 
            if (nums[j] > nums[j + 1]) {
                int temp = nums[j];
                nums[j] = nums[j + 1];
                nums[j + 1] = temp;
            }
        }
    }
}

void display(vector<int>&nums) {
    for (int i = 0; i < nums.size() ; i++) {
        cout << nums[i] << "--";
    }
}
int main() {
    vector<int>nums{ 1,2,3,6,5,4,9,8,7 };
    bubble_sort(nums);
    display(nums);
    return 0;
}

八大排序算法_第1张图片

插入排序

void insert_sort(vector<int>&nums) {
    //12340
    for (int i = 1; i < nums.size();i++) {
        for (int j = i; j > 0;j--) {
            if (nums[j - 1] > nums[j])
                swap(nums[j - 1], nums[j]);
        }
    }
}

八大排序算法_第2张图片

选择排序

void selection_sort(vector<int>&nums) {
    for (int i = 0; i < nums.size();i++) {
        //12543
        int min = i;
        for (int j = i + 1; j < nums.size();j++) {
            if (nums[min] >= nums[j])
                min = j;
        }
        swap(nums[min], nums[i]);
    }
}

八大排序算法_第3张图片

希尔排序

void shell_sort(vector<int>&nums) {
    for (int gap = nums.size() / 2; gap > 0;gap=gap/2) {
        for (int i = gap; i < nums.size();i++) {
            int temp = nums[i];
            int j = i - gap;
            for (; j >= 0 && nums[j] > temp;j=j-gap) {
                nums[j + gap] = nums[j];
            }
            nums[j+gap]=temp;
        }
    }
}

八大排序算法_第4张图片

归并排序

void mergeVector(vector<int>&nums, int begin,int mid, int end) {
    vector<int>temp(end-begin+1, 0);
    int leftBegin = begin, rightBegin = mid+1, tempBegin = 0;
    while (leftBegin<=mid&&rightBegin<=end){
        if (nums[leftBegin] <= nums[rightBegin])
            temp[tempBegin++] = nums[leftBegin++];
        else
            temp[tempBegin++] = nums[rightBegin++];
    }
    while (leftBegin<=mid){
        temp[tempBegin++] = nums[leftBegin++];
    }
    while (rightBegin <= end) {
        temp[tempBegin++] = nums[rightBegin++];
    }
    for (int i = 0; i void mergeSort(vector<int>&nums,int begin,int end) {
    int mid = (begin + end) / 2;
    if (begin1, end);
        mergeVector(nums, begin, mid, end);
    }
}

八大排序算法_第5张图片

快速排序

int partionHelper(vector<int>&nums, int left, int right) {
    int tem = left - 1;
    for (int i = left; i < right;i++) {
        if (nums[i] < nums[right])
            swap(nums[i], nums[++tem]);
    }
    swap(nums[right], nums[++tem]);
    return tem;
}

void quickSort(vector<int>&nums, int left, int right) {
    if (left < right) {
        int tem = partionHelper(nums, left, right);
        quickSort(nums, left, tem - 1);
        quickSort(nums, tem + 1, right);
    }
}

八大排序算法_第6张图片

#

#

你可能感兴趣的:(八大排序算法)