Selection Sort in C: Implementation & Example
Here is an example of C code using selection sort.
#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;
}
Firstly, the code defines a function called selectionSort which accepts an integer array and the length of the array as input. Inside this function, two nested loops are used to iterate through the array, compare elements, find the index of the smallest element, and then swap that element with the current element. Then, in the main function, an integer array arr is defined and the length of the array is calculated. This array and its length are passed as parameters to the selectionSort function, and the sorted array is printed after the sorting is complete.
Running this code will produce:
排序后的数组:
11 12 22 25 34 64 90