Selection Sort in C Language

169Views
No Comments

共计 1338 个字符,预计需要花费 4 分钟才能阅读完成。

Selection sort is a simple in-place comparison-based sorting algorithm that sorts an array by repeatedly finding the minimum element from the unsorted part of the array and moving it to the beginning of the array. Here’s an implementation of the selection sort algorithm in C language:

#include <stdio.h>

void swap(int *xp, int *yp) {
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

void selectionSort(int arr[], int n) {
    int i, j, min_idx;

    // One by one move boundary of unsorted subarray
    for (i = 0; i < n-1; i++) {
        // Find the minimum element in unsorted array
        min_idx = i;
        for (j = i+1; j < n; j++) {
            if (arr[j] < arr[min_idx]) {
                min_idx = j;
            }
        }
        // Swap the found minimum element with the first element
        swap(&arr[min_idx], &arr[i]);
    }
}

int main() {
    int arr[] = {64, 25, 12, 22, 11};
    int n = sizeof(arr)/sizeof(arr[0]);

    selectionSort(arr, n);

    printf("Sorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

In the selectionSort function, we first find the minimum element from the unsorted part of the array and swap it with the first element. We then repeat this process for the remaining subarray until the entire array is sorted.

The swap function is a helper function that exchanges the values of two integer variables using pointers.

In the main function, we create an integer array and call the selectionSort function to sort it. Finally, we print the sorted array to the console.

The time complexity of selection sort is O(n^2), which makes it inefficient for large arrays. However, it has the advantage of being simple to implement and requiring only a small amount of additional memory space.

正文完
 
Amitesh Kumar
Copyright notice: Our original article, by Amitesh Kumar 2023-02-22 publish, total 1338 words.
转载说明:Unless otherwise specified, all articles are published by cc-4.0 protocol. Please indicate the source of reprint.
Comment(No Comments)