租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

c++数组排序的有哪些方法,c++数组排序算法

发布时间:2024-02-05 17:21:10

c++数组排序的有哪些方法

C++中有多种排序数组的方法,以下是其中的一些常见方法:

  1. 冒泡排序(Bubble Sort):通过比较相邻元素的大小,不断交换位置,将较大值逐步“冒泡”到数组的最后。
void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n⑴; i++) {
        for (int j = 0; j < n-i⑴; j++) {
            if (arr[j] > arr[j+1]) {
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}
  1. 选择排序(Selection Sort):每次从未排序的部份中找到最小(或最大)的元素,与未排序部份的第一个元素交换位置。
void selectionSort(int arr[], int n) {
    for (int i = 0; i < n⑴; i++) {
        int minIndex = i;
        for (int j = i+1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        int temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }
}
  1. 插入排序(Insertion Sort):将数组分为已排序部份和未排序部份,每次将未排序部份的第一个元素插入到已排序部份的正确位置。
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. 快速排序(Quick Sort):选择一个基准元素,将数组划分成两个子数组,左侧的元素小于等于基准,右侧的元素大于基准,递归地对子数组进行快速排序。
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++;
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    int temp = arr[i+1];
    arr[i+1] = arr[high];
    arr[high] = temp;
    return i + 1;
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi⑴);
        quickSort(arr, pi+1, high);
    }
}

这些仅仅是一些常见的排序算法,C++中还有其他排序算法的实现。根据实际情况和需求,选择适合的排序算法既能提高排序效力,也能减少资源消耗。