排序算法之二:冒泡、插入、希尔、快排

还是打击太深,面的太水,不然,也不会把这些老黄历再扒出来….
希望多写写能够增加熟练度~~

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

//交换
void swap(int* arr, int x, int y) {
    int tmp = arr[x];
    arr[x] = arr[y];
    arr[y] = tmp;
}
//打印
void print(int* arr, int n) {
    for (int i = 0;i < n;i++) {
        cout << arr[i] << '\t';
    }
}
//简单的交换排序 非正宗的冒泡排序
void BuddleSort(int* arr, int n) {
    int i, j;
    for (i = 0;i < n;i++) {
        for (j = i + 1;j < n;j++) {
            if (arr[i] > arr[j]) {
                swap(arr, i, j);
            }
        }
    }
}
//正宗的冒泡排序
void BuddleSort1(int * arr, int n) {
    int i, j;
    for (i = 0;i < n;i++) {
        for (j = n - 2;j >= i;j--) {
            if (arr[j] > arr[j + 1])
                swap(arr, j, j + 1);
        }
    }
}
//冒泡排序改进
void BuddleSort2(int * arr, int n) {
    int i, j;
    int swap_falg = 1;
    for (i = 0;i < n && swap_falg;i++) {
        swap_falg = 0;
        for (j = n - 2;j >= i;j--) {
            if (arr[j] > arr[j + 1]) {
                swap(arr, j, j + 1);
                swap_falg = 1;
            }

        }
    }
}

//简单选择排序
void  SelectSort(int* arr, int n) {
    int i, j, min;
    for (i = 0;i < n;i++) {
        min = i;
        for (j = i + 1;j < n;j++) {
            if (arr[min] > arr[j])
                min = j;
        }
        if (min != i) {
            swap(arr, i, min);
        }
    }
}
//直接插入排序
void InsertSort(int* arr, int n) {
    int i, j;
    int tmp;
    for (i = 1;i < n;i++) {
        if (arr[i] < arr[i - 1]) {
            tmp = arr[i];
            for (j = i - 1;arr[j] > tmp;j--) {
                arr[j + 1] = arr[j];
            }
            arr[j + 1] = tmp;
        }
    }
}
//希尔排序
void ShellSort(int* arr, int n) {
    int i, j;
    int tmp;
    int increment = n;
    do
    {
        increment = increment / 3 + 1;
        for (i = increment;i < n;i++) {
            if (arr[i] < arr[i - increment]) {
                tmp = arr[i];
                for (j = i - increment;j >= 0 && tmp < arr[j];j -= increment) {
                    arr[j + increment] = arr[j];
                }
                arr[j + increment] = tmp;
            }
        }
    } while (increment > 1);
}


//快速排序
int Partition(int* arr, int low, int high) {
    int pivokey = arr[low];
    int i = 0;
    while (low < high) {
        while (low < high && arr[high] >= pivokey) {
            high--;
        }
        swap(arr, low, high);
        while (low < high && arr[low] <= pivokey) {
            low++;
        }
        swap(arr, low, high);
    }
    return low;
}
void QuickSort(int* arr, int low, int high) {
    int pivot;
    if (low < high) {
        pivot = Partition(arr, low, high);
        QuickSort(arr, low, pivot - 1);
        QuickSort(arr, pivot + 1, high);
    }
}

先到这里~~

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