温馨提示×

c语言选择法排序代码怎么写

小亿
83
2024-02-02 11:17:37
栏目: 编程语言

以下是一个使用选择法排序的C语言代码示例:

#include <stdio.h>

void selectionSort(int arr[], int n) {
    int i, j, minIndex, temp;
    for (i = 0; i < n-1; i++) {
        minIndex = i;
        for (j = i+1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        // 交换当前元素与最小元素
        temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    selectionSort(arr, n);
    printf("排序后的数组:\n");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    return 0;
}

此代码首先定义了一个名为selectionSort的函数,该函数接受一个整数数组和数组的长度作为输入。在这个函数中,使用两个嵌套的循环来遍历数组并比较元素,找到最小的元素的索引,然后将该元素与当前元素交换。然后,在main函数中,我们定义了一个整数数组arr,并计算了数组的长度。我们将该数组和长度作为参数传递给selectionSort函数,并在排序完成后打印出排序后的数组。

运行此代码将输出:

排序后的数组:
11 12 22 25 34 64 90

0