117.info
人生若只如初见

c语言怎么排序一组数

在C语言中,可以使用多种排序算法对一组数进行排序。以下是常见的几种排序算法的示例代码:

  1. 冒泡排序(Bubble Sort):
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]) {
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}
  1. 快速排序(Quick Sort):
void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pivot = partition(arr, low, high);
        quickSort(arr, low, pivot - 1);
        quickSort(arr, pivot + 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++;
            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;
}
  1. 选择排序(Selection Sort):
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;
            }
        }
        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;
    }
}

以上仅是几种常见的排序算法示例,实际应用中还有其他更复杂的排序算法可供选择。根据具体情况选择适合的排序算法可以提高排序的效率。

未经允许不得转载 » 本文链接:https://www.117.info/ask/fe80fAzsLAgJQB10.html

推荐文章

  • C语言怎么连续输入数据

    在C语言中,可以使用循环结构来连续输入数据。一种常见的方式是使用while循环,如下所示:
    #include int main() { int num; while (1) { printf("请输入一个...

  • C语言转义字符如何使用

    C语言中的转义字符是一些特殊的字符序列,它们用来表示一些特殊的含义。以下是一些常用的转义字符及其用法: \n:换行符
    用法:printf(“Hello\nWorld”); ...

  • C语言框架怎么写

    C语言是一种结构化的编程语言,它本身并没有内置的框架。但是,你可以使用一些常用的C语言库和框架来帮助你开发应用程序。下面是一个简单的C语言框架示例:

  • c语言转义字符如何判断是否正确

    在C语言中,转义字符以反斜杠(\)开头,后面跟一个字符或者一组字符。要判断一个转义字符是否正确,可以使用以下方法: 检查反斜杠后面的字符是否是合法的转义字...

  • c语言怎么交换数组元素顺序

    可以通过循环遍历数组并交换相邻元素的位置来实现数组元素的顺序交换。具体做法如下:
    #include void swap(int *a, int *b) { int temp = *a; *a = *b; *b ...

  • android常用的文件系统有哪些

    Android常用的文件系统有以下几种: FAT32:FAT32是一种Windows操作系统中常见的文件系统,支持最大文件大小为4GB,最大分区容量为2TB。 NTFS:NTFS是Windows操作...

  • linux文件系统碎片整理的方法是什么

    在Linux中,可以使用以下几种方法来整理文件系统的碎片: 使用工具进行碎片整理:Linux上有一些工具可以用来整理文件系统的碎片,例如e4defrag(用于ext4文件系统...

  • c++线程池创建及使用的方法是什么

    在C++中,可以使用std::thread和std::vector来创建和管理线程池。以下是一个简单的示例:
    #include #include #include #include #include #include #includ...