C++实现排序算法

  1. 冒泡排序
void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
}
  1. 选择排序
void selectionSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        swap(arr[i], arr[minIndex]);
    }
}
  1. 插入排序
void insertionSort(int arr[], int n) {
    for (int i = 1; i < n; 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;
    }
}
  1. 快速排序
void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

int partition(int arr[], int low, int high) {
    int pivot = arr[high];    
    int i = (low - 1); 
    for (int j = low; j < high; j++) {
        if (arr[j] < pivot) {
            i++;
            swap(arr[i], arr[j]);
        }
    }
    swap(arr[i + 1], arr[high]);
    return (i + 1);
}
  1. 归并排序
#include 

void merge(int arr[], int temp[], int left, int mid, int right) {
    int i = left, j = mid + 1, k = left;
    while (i <= mid && j <= right) {
        if (arr[i] <= arr[j]) {
            temp[k++] = arr[i++];
        } else {
            temp[k++] = arr[j++];
        }
    }
    while (i <= mid) {
        temp[k++] = arr[i++];
    }
    while (j <= right) {
        temp[k++] = arr[j++];
    }
    for (int i = left; i <= right; i++) {
        arr[i] = temp[i];
    }
}

void mergeSort(int arr[], int n) {
    int curr_size;  // 当前子数组的大小
    int left_size;  // 左子数组的大小
    int mid_size;   // 中间子数组的大小
    int right_size; // 右子数组的大小
    for (curr_size = 1; curr_size <= n - 1; curr_size = 2 * curr_size) {
        left_size = curr_size / 2;
        mid_size = curr_size / 2;
        right_size = curr_size;
        int left_half[left_size], mid_half[mid_size], right_half[right_size];
        for (int i = 0; i < left_size; i++) {
            left_half[i] = arr[i];
        }
        for (int i = left_size; i < left_size + mid_size; i++) {
            mid_half[i - left_size] = arr[i];
        }
        for (int i = left_size + mid_size; i < n; i++) {
            right_half[i - left_size - mid_size] = arr[i];
        }
        merge(left_half, arr, 0, left_size - 1, mid_size - 1);
        merge(mid_half, arr, left_size, mid_size - 1, right_size - 1);
        merge(right_half, arr, left_size + mid_size, right_size - 1, n - 1);
    }
}

你可能感兴趣的:(C/C++,排序算法,c++,算法)