使用选择排序法输出排序后的数组C语言
时间: 2024-05-01 12:18:44 浏览: 48
C语言程序设计-编写函数用选择排序法对数组中的数据进行从小到大的排序;
5星 · 资源好评率100%
Sure, I can help you with that! Here's how you can implement selection sort in C to sort an array:
```
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
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
// Example usage
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;
}
```
This will output the sorted array using selection sort in C. Let me know if you have any other questions!
阅读全文