题解 | 对数组元素按照升序或降序进行排序
输入整型数组和排序标识,对其元素按照升序或降序进行排序
https://www.nowcoder.com/practice/dd0c6b26c9e541f5b935047ff4156309
#include <stdio.h> void Bs_sort(int* nums, int numsSize, int sign) { int temp; int flag = 1; if (sign == 0) { for (int i = 0; i < numsSize - 1; i++) { for (int j = numsSize - 1; j > i; j--) { if (nums[j] < nums[j - 1]) { temp = nums[j - 1]; nums[j - 1] = nums[j]; nums[j] = temp; flag = 0; } } if (flag == 1) { break; } } } else { for (int i = 0; i < numsSize - 1; i++) { for (int j = numsSize - 1; j > i; j--) { if (nums[j] > nums[j - 1]) { temp = nums[j - 1]; nums[j - 1] = nums[j]; nums[j] = temp; flag = 0; } } if (flag == 1) { break; } } } for (int i = 0; i < numsSize ; i++) { printf("%d ", nums[i]); } } int main() { int n; scanf("%d", &n); int arr[n]; for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } int flg; scanf("%d", &flg); Bs_sort(arr, n, flg); return 0; }