用选择排序为下列数组排序:
[87, 48, 64, 19, 30, 82, 50, 15, 73, 22, 68, 4, 93, 36, 80, 91, 53, 10, 27]
选择排序(Selection Sort):首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
#include <stdio.h> void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void selectionSort(int arr[], int n) { int i, j, minIndex; for (i = 0; i < n - 1; i++) { minIndex = i; for (j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } if (minIndex != i) { swap(&arr[minIndex], &arr[i]); } } } int main() { int arr[] = {87, 48, 64, 19, 30, 82, 50, 15, 73, 22, 68, 4, 93, 36, 80, 91, 53, 10, 27}; int n = sizeof(arr) / sizeof(arr[0]); selectionSort(arr, n); printf("Sorted array: \n"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }