How is the selection sort method used in the C language?

In C programming language, you can use the selection sort algorithm to sort an array. The basic idea of selection sort is to select the smallest (or largest) element from the unsorted portion each time and place it at the end of the sorted portion.

Below is an example code of using the selection sort algorithm to sort an array of integers:

#include <stdio.h>

void selectionSort(int arr[], int n) {

    int i, j, min_idx, temp;

    // 遍历整个数组

    for (i = 0; i < n - 1; i++) {

        // 找到未排序部分的最小元素位置

        min_idx = i;

        for (j = i + 1; j < n; j++) {

            if (arr[j] < arr[min_idx])

                min_idx = j;

        }

        // 将最小元素与当前位置交换

        temp = arr[i];

        arr[i] = arr[min_idx];

        arr[min_idx] = temp;

    }

}

int main() {

    int arr[] = {64, 25, 12, 22, 11};

    int n = sizeof(arr) / sizeof(arr[0]);

    int i;

    printf("原始数组:");

    for (i = 0; i < n; i++)

        printf("%d ", arr[i]);

    selectionSort(arr, n);

    printf("\n排序后的数组:");

    for (i = 0; i < n; i++)

        printf("%d ", arr[i]);

    return 0;

}

In the above code, the `selectionSort()` function is used to implement the selection sort algorithm. Within the `main()` function, an integer array `arr` is created, and the length of the array `n` is calculated. Then, the original array is outputted, and the `selectionSort()` function is called to sort the array. Finally, the sorted array is outputted.

The code will produce:

原始数组:64 25 12 22 11 

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

This is an example of sorting an array using the selection sort algorithm in the C language.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds